17

我正在尝试实现 OWIN 不记名令牌授权,并基于本文。但是,我在不记名令牌中还需要一条额外的信息,但我不知道如何实现。

在我的应用程序中,我需要从不记名令牌中推断出用户信息(比如 userid)。这很重要,因为我不希望授权用户能够充当另一个用户。这是可行的吗?它甚至是正确的方法吗?如果用户 ID 是 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);
    }
}

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

4

3 回答 3

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();
        }
  }

可以在这里找到一篇详细的好文章。在这个博客系列
中可以找到更好的解释。

更新

我做了一些挖掘和webstuff是正确的。

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

context.Rejected();
context.SetError("invalid_client", "The information provided are not valid !");
return;

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

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

在此处输入图像描述

使用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);
            }
    }
});
于 2014-06-22T11:17:49.090 回答
10

附带说明一下,如果要设置自定义错误消息,则必须交换context.Rejectedand的顺序context.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();

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

    // Client could not be validated.
    context.Rejected();
    context.SetError("invalid_client", "Client credentials are invalid.");
于 2015-10-30T02:06:59.823 回答
0

只是为了补充 LeftyX 的答案,这是在上下文被拒绝后如何完全控制发送给客户端的响应的方法。注意代码注释。

基于 Greg P 的原始答案,并进行了一些修改

第 1 步:创建一个作为中间件的类

using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, System.Object>,
System.Threading.Tasks.Task>;

命名空间 SignOnAPI.Middleware.ResponseMiddleware {

public class ResponseMiddleware 
{
    AppFunc _next;
    ResponseMiddlewareOptions _options;

    public ResponseMiddleware(AppFunc nex, ResponseMiddlewareOptions options)
    {
        _next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        var context = new OwinContext(environment);

        await _next(environment);

        if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey("Change_Status_Code"))
        {
            //read the status code sent in the response
            var headerValues = context.Response.Headers.GetValues("Change_Status_Code");

            //replace the original status code with the new one
            context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());

            //remove the unnecessary header flag
            context.Response.Headers.Remove("Change_Status_Code");
        }
    }
}

Step2:创建扩展类(可以省略)。

此步骤是可选的,可以修改为接受可以传递给中间件的选项。

public static class ResponseMiddlewareExtensions
{
    //method name that will be used in the startup class, add additional parameter to accept middleware options if necessary
    public static void UseResponseMiddleware(this IAppBuilder app)
    {
        app.Use<ResponseMiddleware>();
    }
}

第 3 步:在您的实现中修改GrantResourceOwnerCredentials方法OAuthAuthorizationServerProvider

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        if (<logic to validate username and password>)
        {
            //first reject the context, to signify that the client is not valid
            context.Rejected();

            //set the error message
            context.SetError("invalid_username_or_password", "Invalid userName or password" );

            //add a new key in the header along with the statusCode you'd like to return
            context.Response.Headers.Add("Change_Status_Code", new[] { ((int)HttpStatusCode.Unauthorized).ToString() }); 
            return;
        }
    }

Step4:在启动类中使用这个中间件

public void Configuration(IAppBuilder app)
{
    app.UseResponseMiddleware();

    //configure the authentication server provider
    ConfigureOAuth(app);

    //rest of your code goes here....
}
于 2016-10-02T09:42:19.830 回答