我正在尝试实现OWIN承载令牌授权,并基于this article . 但是,有's one additional piece of information I need in bearer token that I don'知道如何实现 .
在我的应用程序中,我需要从持有者令牌中推断出用户信息(比如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);
}
}
我认为可以覆盖授权/身份验证以适应我的需要吗?
3 回答
你的代码似乎缺少一些东西 .
你没有验证你的客户 .
您应该实现ValidateClientAuthentication并在那里检查您的客户端凭据 .
这就是我做的:
一篇很好的文章可以找到here .
在blog系列中可以找到更好的解释 .
UPDATE :
我做了一些挖掘,webstuff是对的 .
为了将
errorDescription
传递给客户端,我们需要在使用SetError
设置错误之前拒绝:或者我们可以在描述中通过序列化的json对象扩展它:
使用
javascript/jQuery
客户端,我们可以反序列化文本响应并读取扩展消息:另外,如果要设置自定义错误消息,则必须交换
context.Rejected
和context.SetError
的顺序 .如果在
context.SetError
之后放置context.Rejected
,则属性context.HasError
将重置为 false ,因此使用它的正确方法是:只是为了添加LeftyX的答案,这里是你可以完全控制上下文被拒绝后发送给客户端的响应 . 注意代码注释 .
Based on Greg P's original answer,进行了一些修改
Step1: Create a class which will act as your middleware
namespace SignOnAPI.Middleware.ResponseMiddleware {
Step2 : Create the extensions class (Can be omitted).
此步骤是可选的,可以修改为接受可以传递给中间件的选项 .
Step3: Modify GrantResourceOwnerCredentials method in your OAuthAuthorizationServerProvider implementation
Step4: Use this middleware in the startup class