javascript - C# Owin handle 401 access token errors and regenerate access tokens using refresh token
问题描述
I 'm new to this forum and I expect a lot of help from the experts, we have a project where OWIN authentication is implemented in C# and we have internal tool for UI(in old angular language, javascript) there seems to be lot of flaws, below are some issues.
If access token gets expired and there is a call to access protected resource, here the call won't complete so how can we make that call complete post generating a new access token using refresh token, this needs to be handled in UI or service side, any code pointers ?
Is it a good practice to generate access token using refresh token before access token expiry interval in UI?
Api's are also consumed by windows service so if access token expires and the service hit's any api with the expired token it will throw unauthorized however same question how to create token on fly and make that call complete.
Any help on this, would be really greatful so, awaiting for your replies, sample code shown below.
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
};
解决方案
1)我不能真正提供任何代码指针,因为我不知道您的 Angular 版本,但到目前为止我所做的方式是为您的请求提供某种拦截器。它查找来自 API 的任何未授权状态代码,缓存请求,尝试命中刷新令牌端点,如果刷新请求成功,则使用新的访问令牌重新发送缓存的请求,如果刷新请求失败,则要求用户再次验证。
您还可以尝试实现一个拦截器,该拦截器检查访问令牌到期日期并在剩余 5 分钟有效期时点击刷新令牌端点。
2)我会说刷新令牌通常用于已经过期的访问令牌。
3) 我不知道您对这些 Windows 服务有多少控制权,但据我所知,刷新令牌流应该在客户端处理。
推荐阅读
- swift - 隐式展开时我的集合视图为零?
- c++ - 我是否必须手动将哈希表的值输入到我的代码中,或者我可以从文本文件中读取它们
- python - matplotlib条形图中的条形宽度不一样?
- python - OpenCV 相同的图像返回不同的结果
- javascript - 多个属性的 CSS 过渡
- javascript - 是否有任何 TC39 提案将属性从一个对象分配给另一个对象?
- sparql - JENA 中的 OWL 查询
- python - 如何使用 Pycharm 运行 fast-api 服务器?
- node.js - 当我尝试使用 uuid 包时,如何解决“意外令牌'导出'”错误?
- pandas - Pandas Correlation - 如何使用 df.corr() 忽略两列中的 0