为Bearer授权添加额外的逻辑

Ech*_*ban 17 c# oauth-2.0 asp.net-web-api owin bearer-token

我正在尝试实施OWIN持有人令牌授权,并基于这篇文章.但是,在承载令牌中我需要一条额外的信息,我不知道如何实现.

在我的应用程序中,我需要从持有者令牌中推断出用户信息(比如userid).这很重要,因为我不希望授权用户能够充当其他用户.这可行吗?它甚至是正确的方法吗?如果用户标识是guid,那么这很简单.在这种情况下,它是一个整数.授权用户可能只是通过猜测/暴力来冒充他人,这是不可接受的.

看看这段代码:

public void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider()
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

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

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为可以覆盖授权/身份验证以适应我的需要吗?

Lef*_*tyX 18

你的代码似乎缺少一些东西.
你没有验证你的客户.

您应该实现ValidateClientAuthentication并在那里检查客户端的凭据.

这就是我做的:

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
        string clientId = string.Empty;
        string clientSecret = string.Empty;

        if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) 
        {
            context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
            context.Rejected();
            return;
        }

        ApplicationDatabaseContext dbContext = context.OwinContext.Get<ApplicationDatabaseContext>();
        ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        if (dbContext == null)
        {
            context.SetError("server_error");
            context.Rejected();
            return;
        }

        try
        {
            AppClient client = await dbContext
                .Clients
                .FirstOrDefaultAsync(clientEntity => clientEntity.Id == clientId);

            if (client != null && userManager.PasswordHasher.VerifyHashedPassword(client.ClientSecretHash, clientSecret) == PasswordVerificationResult.Success)
            {
                // Client has been verified.
                context.OwinContext.Set<AppClient>("oauth:client", client);
                context.Validated(clientId);
            }
            else
            {
                // Client could not be validated.
                context.SetError("invalid_client", "Client credentials are invalid.");
                context.Rejected();
            }
        }
        catch (Exception ex)
        {
            string errorMessage = ex.Message;
            context.SetError("server_error");
            context.Rejected();
        }
  }
Run Code Online (Sandbox Code Playgroud)

充满细节的好文章,可以发现在这里.
在这个博客系列中可以找到更好的解释.

更新:

我做了一些挖掘和webstuff是对的.

为了传递errorDescription给客户端,我们需要在我们设置错误之前拒绝SetError:

context.Rejected();
context.SetError("invalid_client", "The information provided are not valid !");
return;
Run Code Online (Sandbox Code Playgroud)

或者我们可以在描述中通过序列化的json对象扩展它:

context.Rejected();
context.SetError("invalid_client", Newtonsoft.Json.JsonConvert.SerializeObject(new { result = false, message = "The information provided are not valid !" }));
return;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用javascript/jQuery客户端,我们可以反序列化文本响应并读取扩展消息:

$.ajax({
    type: 'POST',
    url: '<myAuthorizationServer>',
    data: { username: 'John', password: 'Smith', grant_type: 'password' },
    dataType: "json",
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    xhrFields: {
        withCredentials: true
    },
    headers: {
        'Authorization': 'Basic ' + authorizationBasic
    },  
    error: function (req, status, error) {
            if (req.responseJSON && req.responseJSON.error_description)
            {
               var error = $.parseJSON(req.responseJSON.error_description);
                    alert(error.message);
            }
    }
});
Run Code Online (Sandbox Code Playgroud)


web*_*uff 10

在一个侧面说明,如果你想设置自定义错误消息,你必须交换的顺序context.Rejectedcontext.SetError.

    // Summary:
    //     Marks this context as not validated by the application. IsValidated and HasError
    //     become false as a result of calling.
    public virtual void Rejected();
Run Code Online (Sandbox Code Playgroud)

如果你放置context.Rejected之后context.SetError该属性context.HasError将被重置为false,因此使用它的正确方法是:

    // Client could not be validated.
    context.Rejected();
    context.SetError("invalid_client", "Client credentials are invalid.");
Run Code Online (Sandbox Code Playgroud)