【问题标题】:Token authentication against custom database in WebAPI针对 WebAPI 中的自定义数据库的令牌身份验证
【发布时间】:2017-04-07 14:39:45
【问题描述】:

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

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。

我做错了什么?:)

【问题讨论】:

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


    【解决方案1】:

    任何有同样问题的人,只要按照这篇文章,它展示了如何覆盖 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 2011-03-18
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      相关资源
      最近更新 更多