繁体   English   中英

OAuthAuthorizationServerProvider:验证客户端承载令牌

[英]OAuthAuthorizationServerProvider: validate client bearer token

我能够通过验证传入的用户名和密码来生成令牌。 startup.cs我有这个

public class Startup

{

    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(100),
            Provider = new MYAuthorizationServerProvider(),
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
        {
            Provider = new OAuthBearerAuthenticationProvider()
        });

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }

}

MyAuthorizationsServiceProvider我有

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        var userServices = new UserService();
        var user = await userServices.ValidateUser(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "Provided username and password is incorrect");
            return;
        }
        else
        {

            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            identity.AddClaim(new Claim("username", user.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            context.Validated(identity);
        }

    }

到目前为止,这一切都很好。 我有一个只能由管理员角色访问的控制器,它对生成的令牌工作正常。

现在让我们假设我已经取消了该特定用户在后端的用户角色或停用了该用户。 现在令牌不应该对那个特定的控制器起作用,或者在用户被停用时使身份验证无效。 Oauth 如何知道后端更改以及它如何验证?

如果有人可以通过一些示例提供答案,那将非常有帮助。

我也有公共override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)但由于某种原因这不会启动。

Oauth 如何知道后端更改以及它如何验证?

它只会在用户登录时针对后端验证用户名和密码。之后,根据客户端随请求传递的令牌设置主体和声明。

一种选择是创建一个自定义授权过滤器,用于在每个请求中根据后端验证用户,但不建议这样做,因为这会在请求时间上非常昂贵。

更好的选择是将令牌的有效时间设置为低于 100 天的数字AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),并将RefreshTokenProvider添加到 OAuthAuthorizationServer。 然后在该提供程序中针对后端重新验证用户。 您可以在此处阅读有关如何实现刷新提供程序的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM