【发布时间】:2017-12-06 04:57:38
【问题描述】:
我正在使用 ASP.NET API2 和 OWIN 实现 OAuth 2 刷新令牌,以下代码是我的 OAuthAuthorizationOptions
public static OAuthAuthorizationServerOptions AuthorizationServerOptions
{
get
{
if (_AuthorizationServerOptions == null)
{
_AuthorizationServerOptions = new OAuthAuthorizationServerOptions()
{
AuthenticationType = OAuthDefaults.AuthenticationType,
AllowInsecureHttp = true,
TokenEndpointPath = new PathString(AuthSettings.TokenEndpoint),
AuthorizeEndpointPath = new PathString(AuthSettings.AuthorizeEndpoint),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AuthSettings.TokenExpiry),
Provider = new CustomOAuthAuthorizationServerProvider(AuthSettings.PublicClientId),
// TODO: Remove the dependency with Thinktecture.IdentityModel library here
AccessTokenFormat = new CustomJWTFormat(),
RefreshTokenProvider = new CustomRefreshTokenProvider()
};
}
return _AuthorizationServerOptions;
}
}
这是我的 CustomRefreshTokenProvider 类
public override Task CreateAsync(AuthenticationTokenCreateContext context)
{
var identifier = context.Ticket.Identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (identifier == null || string.IsNullOrEmpty(identifier.Value))
{
return Task.FromResult<object>(null);
}
var refreshToken = HashHelper.Hash(Guid.NewGuid().ToString("n"));
var tokenIssued = DateTime.UtcNow;
var tokenExpire = DateTime.UtcNow.AddSeconds(AuthSettings.RefreshTokenExpiry);
context.Ticket.Properties.IssuedUtc = tokenIssued;
context.Ticket.Properties.ExpiresUtc = tokenExpire;
context.Ticket.Properties.AllowRefresh = true;
var protectedTicket = context.SerializeTicket();
AuthService.AddUserRefreshTokenSession(
identifier.Value,
refreshToken,
tokenIssued,
tokenExpire,
protectedTicket);
context.SetToken(refreshToken);
return Task.FromResult<object>(null);
}
public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var refToken = context.Token;
var protectedTicket = AuthService.GetProtectedTicket(refToken);
if (!string.IsNullOrEmpty(protectedTicket))
{
context.DeserializeTicket(protectedTicket);
}
return Task.FromResult<object>(null);
}
我使用邮递员将 POST 请求发送到令牌端点,如下所示 Postman refresh token 服务器返回 400 错误请求状态码。 我调试了一下,发现 context.DeserializeTicket(protectedTicket) 抛出异常
Exception thrown: 'System.Security.Cryptography.CryptographicException' in System.Web.dll
我认为这不是过期问题,因为 AuthSettings.RefreshTokenExpiry 是从现在起 30 天。 我还尝试将机器密钥添加到我的 web.config OAuth Refresh Token does not deserialize / invalid_grant
但它仍然无法正常工作。
有人有想法吗? 任何解决方案都将受到高度赞赏。
【问题讨论】:
-
你找到解决办法了吗,我也有同样的问题。
-
@Amin K 抱歉回复晚了,我刚回答,是你需要的吗?
标签: asp.net asp.net-web-api2 owin