0

我正在尝试对我自己的数据库实施令牌身份验证。我的配置方法是

public void ConfigureAuth(IAppBuilder app)
{
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new CustomOAuthProvider(),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
}

如您所见,我使用了 CustomOAuthProvider 类,它覆盖了 GrantResourceOwnerCredentials 方法,如下所示

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

        IUsersService userService = DependencyResolver.Current.GetService<IUsersService>();
        if (!userService.CheckCredentials(context.UserName, context.Password))
        {
            context.SetError("invalid_grant", "The user name or password is incorrect");
            return Task.FromResult<object>(null);
        }

        var identity = new ClaimsIdentity("JWT");

        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

        var props = new AuthenticationProperties(new Dictionary<string, string>
        {
            {
                "audience", context.ClientId ?? string.Empty
            }
        });

        var ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);
        return Task.FromResult<object>(null);
    }
}

但是每当我通过 Fiddler 请求令牌时,我都会收到 400 = Bad request。 在此处输入图像描述

我究竟做错了什么 ?:)

4

1 回答 1

0

任何有同样麻烦的人,只要按照这篇文章,它展示了如何覆盖 GrantResourceOwnerCredentials 方法,以便一切正常:

http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-password-grant-type-token-endpoint

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var user = userService.GetUser(context.UserName, context.Password);
    var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
    var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
    context.Validated(ticket);
    return base.GrantResourceOwnerCredentials(context);
}
于 2016-11-23T15:45:11.353 回答