2014-11-17 20 views
16

Sto utilizzando Owin e ASP.NET Identity per utilizzare i token OAuth per proteggere i miei metodi API Web. Il sottosistema token è configurato come tale:Genera token nel controller

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()); 

E le grandi opere per la richiesta di token basati su username/password e quindi consumando quelle pedine. Tuttavia, poiché l'utente è già autenticato quando si colpisce il controller che esegue il rendering della SPA, mi piacerebbe generare il token nella mia vista e passarlo al codice Javascript, invece di dover accedere di nuovo nella SPA.

Quindi la mia domanda è: come posso generare manualmente il mio token in modo che possa includerlo nella mia visualizzazione SPA?

risposta

41

È possibile generare token di accesso all'interno di un controllore chiamando OAuthBearerOptions.AccessTokenFormat.Protect(ticket) e il codice sarà come di seguito:

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

ed è necessario per dichiararlo OAuthBearerOptions come static Proprietà della classe Startup.cs

Ma se stai cercando di implementare l'aggiornamento silenzioso per il token di accesso senza richiedere all'utente di effettuare nuovamente il login, allora dovresti prendere in considerazione l'implementazione della concessione del token di aggiornamento, non farlo come il tuo suggerimento. Puoi leggere il mio dettagliato blog post su come generare i token di aggiornamento in SPA creati con AngularJS.

Spero che questo risponda alla tua domanda.

+1

In API Web ASP.NET 2 questo è già statico e ora è stato rinominato da 'OAuthBearerOptions' a' OAuthOptions', quindi ora 'Startup.OAuthOptions.AccessTokenFormat.Protect (ticket)'. – Fred

+1

È possibile impostare la proprietà 'ExpiresUtc' su' Startup.OAuthOptions.AccessTokenExpireTimeSpan'. – Fred

+3

Come generare un token di aggiornamento tramite il controller? –

Problemi correlati