Generate token in controller

前端 未结 1 550
栀梦
栀梦 2020-12-23 21:45

I\'m using Owin and ASP.NET Identity to use OAuth tokens for securing my Web API methods. The token subsystem is set up as such:

var oauthOptions = new OAuth         


        
相关标签:
1条回答
  • 2020-12-23 22:36

    You can generate access token inside a controller by calling OAuthBearerOptions.AccessTokenFormat.Protect(ticket) and the code will look as the below:

           private JObject GenerateLocalAccessTokenResponse(string userName)
        {
    
            var tokenExpiration = TimeSpan.FromDays(1);
    
            ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
    
            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
    
            var props = new AuthenticationProperties()
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };
    
            var ticket = new AuthenticationTicket(identity, props);
    
            var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
    
            JObject tokenResponse = new JObject(
                                        new JProperty("userName", userName),
                                        new JProperty("access_token", accessToken),
                                        new JProperty("token_type", "bearer"),
                                        new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                                        new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                                        new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
        );
    
            return tokenResponse;
        }
    

    And you need to declare you OAuthBearerOptions as static property in class Startup.cs

    But if you are looking to implement silent refresh for access token without requesting the user to login again, then you should consider implementing refresh token grant, do not do it like the way you suggested. You can read my detailed blog post on how to generate refresh tokens in SPA built with AngularJS.

    Hope this answers your question.

    0 讨论(0)
提交回复
热议问题