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 OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/Token"),
Provider = new SimpleAuthorizationServerProvider(),
AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1")),
RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1")),
AccessTokenProvider = new AuthenticationTokenProvider(),
RefreshTokenProvider = new AuthenticationTokenProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
It works great for requesting tokens based on username/password and then consuming those tokens. However, since the user is already authenticated when hitting the controller that renders the SPA, I would like to generate the token in my view and pass it on to the Javascript code, instead of having to log in again in the SPA.
So my question is: how do I manually generate my token so I can include it in my SPA view?
You can generate access token inside a controller by calling
OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
and the code will look as the below:And you need to declare you
OAuthBearerOptions
asstatic
property in class Startup.csBut 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.