【发布时间】:2014-01-05 10:09:05
【问题描述】:
我正在使用 Visual Studio 2013 附带的 Web Api 2 模板,它有一些 OWIN 中间件来进行用户身份验证等。
在OAuthAuthorizationServerOptions 中,我注意到 OAuth2 服务器设置为分发 14 天后过期的令牌
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(PublicClientId,UserManagerFactory) ,
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
这不适合我的最新项目。我想分发可以使用 refresh_token 刷新的短暂的 bearer_tokens
我在谷歌上搜索了很多,但找不到任何有用的东西。
所以这就是我设法达到的程度。我现在已经达到了“我现在做WTF”的地步。
我写了一个RefreshTokenProvider,它根据OAuthAuthorizationServerOptions 类的RefreshTokenProvider 属性实现IAuthenticationTokenProvider:
public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
var guid = Guid.NewGuid().ToString();
_refreshTokens.TryAdd(guid, context.Ticket);
// hash??
context.SetToken(guid);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(context.Token, out ticket))
{
context.SetTicket(ticket);
}
}
public void Create(AuthenticationTokenCreateContext context)
{
throw new NotImplementedException();
}
public void Receive(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
}
}
// Now in my Startup.Auth.cs
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(PublicClientId,UserManagerFactory) ,
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(2),
AllowInsecureHttp = true,
RefreshTokenProvider = new RefreshTokenProvider() // This is my test
};
所以现在当有人请求bearer_token 我现在发送refresh_token,这很棒。
那么现在我如何使用这个 refresh_token 来获得一个新的bearer_token,大概我需要向我的令牌端点发送一个请求并设置一些特定的 HTTP 标头?
只是在我输入时大声思考...我应该在我的SimpleRefreshTokenProvider 中处理 refresh_token 到期吗?客户如何获得新的refresh_token?
我真的可以阅读一些材料/文档,因为我不想弄错,并且想遵循某种标准。
【问题讨论】:
-
有一个关于使用 Owin 和 OAuth 实现刷新令牌的精彩教程:bitoftech.net/2014/07/16/…
标签: c# asp.net-web-api oauth-2.0 asp.net-identity owin