首页 > 解决方案 > 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.

  1. 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 ?

  2. Is it a good practice to generate access token using refresh token before access token expiry interval in UI?

  3. 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
    };

标签: javascriptc#asp.net-mvcsecurityowin

解决方案


1)我不能真正提供任何代码指针,因为我不知道您的 Angular 版本,但到目前为止我所做的方式是为您的请求提供某种拦截器。它查找来自 API 的任何未授权状态代码,缓存请求,尝试命中刷新令牌端点,如果刷新请求成功,则使用新的访问令牌重新发送缓存的请求,如果刷新请求失败,则要求用户再次验证。

您还可以尝试实现一个拦截器,该拦截器检查访问令牌到期日期并在剩余 5 分钟有效期时点击刷新令牌端点。

2)我会说刷新令牌通常用于已经过期的访问令牌。

3) 我不知道您对这些 Windows 服务有多少控制权,但据我所知,刷新令牌流应该在客户端处理。


推荐阅读