2014-05-14 9 views
10

Web API 2 OWIN Bearer token authentication - AccessTokenFormat null?Qual è l'implementazione OAuth AccessTokenFormat predefinita in OWIN per l'host IIS?

Il default/endpoint token funziona bene e ho potuto ottenere il token da lì, ma ho bisogno di utilizzare il metodo AccessTokenFormat.Protect su un biglietto per generare access token per externalLogin.

Fondamentalmente la mia implementazione è praticamente la stessa di questa, e ho riscontrato lo stesso problema di AccessTokenFormat è null. Dal documentation si dice: formato

I dati utilizzati per proteggere le informazioni contenute nel token di accesso. Se non viene fornito dall'applicazione, il provider di protezione dati predefinito dipende dal server host. L'host SystemWeb su IIS utilizzerà la protezione dei dati delle chiavi della macchina ASP.NET e HttpListener e altri server self-hosted utilizzeranno la protezione dei dati DPAPI. Se viene assegnato un diverso fornitore o formato di token di accesso, è necessario assegnare un'istanza compatibile alla proprietà OAuthBearerAuthenticationOptions.AccessTokenProvider o OAuthBearerAuthenticationOptions.AccessTokenFormat del server di risorse.

Mi sembra che se AccessTokenFormat non è assegnato, l'host fornirebbe un'implementazione di base per esso. Ma non vedo che funzioni qui. C'è un modo per trovare l'implementazione predefinita di ISecureDataFormatAccessTokenFormat e assegnarla manualmente alla variabile?

Oppure qualcuno ha altre idee su come risolverlo?

UPDATE: ottengo il codice sorgente per katana e trovare la classe OAuthAuthorizationServerMiddleware, dal codice sorgente ho potuto vedere il seguente codice:

if (Options.AccessTokenFormat == null) 
     { 
      IDataProtector dataProtecter = app.CreateDataProtector(
       typeof(OAuthAuthorizationServerMiddleware).Namespace, 
       "Access_Token", "v1"); 
      Options.AccessTokenFormat = new TicketDataFormat(dataProtecter); 
     } 

Nel mio Startup.Auth, qui è il mio codice:

 static Startup() 
    { 
     PublicClientId = "self"; 

     UserManagerFactory =() => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 

     OAuthOptions = new OAuthAuthorizationServerOptions() 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      AllowInsecureHttp = true 
     }; 

     OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
     OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat; 
     OAuthBearerOptions.AccessTokenProvider = OAuthOptions.AccessTokenProvider; 
     OAuthBearerOptions.AuthenticationMode = OAuthOptions.AuthenticationMode; 
     OAuthBearerOptions.AuthenticationType = OAuthOptions.AuthenticationType; 
     OAuthBearerOptions.Description = OAuthOptions.Description; 

     OAuthBearerOptions.Provider = new CustomBearerAuthenticationProvider(); 
     OAuthBearerOptions.SystemClock = OAuthOptions.SystemClock; 
    } 

    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 


     app.UseOAuthAuthorizationServer(OAuthOptions); 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(OAuthOptions); 
     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     // Configure the sign in cookie 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      Provider = new CookieAuthenticationProvider 
      { 
       OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
      } 
     }); 
     // Use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

}

ho anche il seguente in WebApiConfig

// Web API configuration and services 
     // Configure Web API to use only bearer token authentication. 
     config.SuppressDefaultHostAuthentication(); 
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 

Io non sono sicuro perché app.UseOAuthAuthorizationServer(OAuthOptions); non è l'impostazione del accessTokenFormat

risposta

10

non sono sicuro perché non è l'impostazione in modo corretto, ma tiro fuori il codice e assegnare la mia auto. Ecco come funziona il mio codice finale:

 public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 


     OAuthOptions = new OAuthAuthorizationServerOptions() 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), 
      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 
     }; 

     OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
     OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat; 
     OAuthBearerOptions.AccessTokenProvider = OAuthOptions.AccessTokenProvider; 
     OAuthBearerOptions.AuthenticationMode = OAuthOptions.AuthenticationMode; 
     OAuthBearerOptions.AuthenticationType = OAuthOptions.AuthenticationType; 
     OAuthBearerOptions.Description = OAuthOptions.Description; 

     OAuthBearerOptions.Provider = new CustomBearerAuthenticationProvider(); 
     OAuthBearerOptions.SystemClock = OAuthOptions.SystemClock; 

     app.UseOAuthAuthorizationServer(OAuthOptions); 
     app.UseOAuthBearerAuthentication(OAuthBearerOptions); 

     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     // Configure the sign in cookie 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      Provider = new CookieAuthenticationProvider 
      { 
       OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
      } 
     }); 
     // Use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 
     } 
Problemi correlati