简体   繁体   中英

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

1) I cannot really provide any code pointers since I don't know your Angular version, but the way I have done it up until now is having some sort of Interceptor for your requests. It looks for any Unauthorized status codes coming from the API, caches the request, tries to hit the refresh token endpoint and resends the cached request with the new access token if the refresh request was successful, if the refresh request failed, ask the user to authenticate again.

You can also try to implement an interceptor that inspects the access token expiry date and hits the refresh token endpoint if it has 5 minutes of validity left.

2) I'd say that refresh tokens are typically used for already expired access tokens.

3) I don't know how much control you have over those Windows Services, but to my knowledge, the refresh token flow is supposed to be handled on the client-side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM