OAuthAuthorizationServerProvider C#:验证客户端Barer令牌

时间:2018-02-09 03:20:32

标签: c# authentication oauth-2.0

我能够通过验证传入的用户名和密码来生成令牌。 在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);
        }

    }

直到现在这一切都很好。我有一个只能由Admin角色访问的控制器,它适用于生成的令牌。

现在让我们假设我已经删除了该特定用户后端的用户角色,或者停用了该用户。现在,令牌不适用于该特定控制器,或者在用户停用时使身份验证无效。 Oauth如何知道后端的变化以及它如何验证?

如果有人可以通过一些非常有用的例子提供答案。

我也有公开override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context),但由于某种原因,这不会激发。

1 个答案:

答案 0 :(得分:0)

  

Oauth如何知道后端的变化及其如何验证?

当用户登录时,它将仅针对后端验证用户名和密码。之后,根据客户端传递的令牌设置原则和声明。

一种选择是创建一个自定义授权过滤器,该过滤器在每个请求中针对后端验证用户,但不建议这样做,因为在请求时间内这将是非常昂贵的。

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

相关问题