对WebAPI中的自定义数据库进行令牌身份验证

时间:2016-11-23 14:21:30

标签: .net asp.net-web-api http-token-authentication

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

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请求。 enter image description here

我做错了什么?:)

1 个答案:

答案 0 :(得分: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);
}