5

Sto lavorando attraverso alcuni MVC ASP.NET 6 e 5 campioni e sto avendo problemi a trovare alcuna documentazione degno sull'uso gettoni al portatore per garantire API. Sono in grado di rendere tali campioni lavorano con VS 2013, MVC 5, ma non riesco a porta questi oltre a VS 2015 e MVC 6. Qualcuno sa di eventuali buoni campioni di attuazione gettoni al portatore in MVC 6 al fine di garantire API?Come utilizzare i token bearer con l'API MVC 6?

+0

FYI, ASP.NET MVC 6 (come parte di ASP.NET 5) doesn' t hanno ancora il supporto integrato per i token bearer, ma il team di ASP.NET sta esaminando questo aspetto. – Eilon

+0

Ho sospettato tanto, grazie per la tua risposta! –

risposta

2

per autenticare una richiesta utilizzando i token al portatore, si può tirare giù il pacchetto Microsoft.AspNet.Security.OAuthBearer. Quindi, è possibile aggiungere il OAuthBearerAuthenticationMiddleware middleware per la pipeline utilizzando il metodo UseOAuthBearerAuthentication estensione.

Esempio:

public void Configure(IApplicationBuilder app) 
{ 

    // ... 

    app.UseOAuthBearerAuthentication(options => 
    { 
     options.Audience = "Redplace-With-Real-Audience-Info"; 
     options.Authority = "Redplace-With-Real-Authority-Info"; 
    }); 
} 

Inoltre, uno sguardo ai WebApp-WebAPI-OpenIdConnect-AspNet5 campione.

0

Ho implementato una singola applicazione pagina con l'attuazione di autenticazione basata su token utilizzando MVC 6, OpenID e il quadro front end Aurelia. In Startup.cs, il metodo di configurazione si presenta in questo modo:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 


    app.UseIISPlatformHandler(); 

    // Add a new middleware validating access tokens. 
    app.UseJwtBearerAuthentication(options => { 
     // Automatic authentication must be enabled 
     // for SignalR to receive the access token. 
     options.AutomaticAuthenticate = true; 

     // Automatically disable the HTTPS requirement for development scenarios. 
     options.RequireHttpsMetadata = !env.IsDevelopment(); 

     // Note: the audience must correspond to the address of the SignalR server. 
     options.Audience = clientUri; 

     // Note: the authority must match the address of the identity server. 
     options.Authority = serverUri; 

    }); 

    // Add a new middleware issuing access tokens. 
    app.UseOpenIdConnectServer(options => { 
     options.Provider = new AuthenticationProvider(); 
    }); 

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); 

    app.UseStaticFiles(); 

    app.UseMvc(routes => 
    { 
     routes.MapRoute(
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
    }); 
} 

Il provider di autenticazione è definita in questo modo:

public class AuthenticationProvider : OpenIdConnectServerProvider 
    { 
     public override Task ValidateClientAuthentication(ValidateClientAuthenticationContext context) 
     { 
      if (context.ClientId == "AureliaNetAuthApp") 
      { 
       // Note: the context is marked as skipped instead of validated because the client 
       // is not trusted (JavaScript applications cannot keep their credentials secret). 
       context.Skipped(); 
      } 

      else { 
       // If the client_id doesn't correspond to the 
       // intended identifier, reject the request. 
       context.Rejected(); 
      } 

      return Task.FromResult(0); 
     } 

     public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) 
     { 
      var user = new { Id = "users-123", Email = "[email protected]", Password = "AureliaNetAuth" }; 

      if (context.UserName != user.Email || context.Password != user.Password) 
      { 
       context.Rejected("Invalid username or password."); 

       return Task.FromResult(0); 
      } 

      var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme); 
      identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "id_token token"); 
      identity.AddClaim(ClaimTypes.Name, user.Email, "id_token token"); 

      context.Validated(new ClaimsPrincipal(identity)); 

      return Task.FromResult(0); 
     } 
    } 

Questo definisce un endpoint di token che può essere raggiunto alla URL /connect/token.

Quindi richiedere un token dal lato client, ecco il codice javascript, tratto dal AuthService in authSvc.js:

login(username, password) { 
    var baseUrl = yourBaseUrl; 

    var data = "client_id=" + yourAppClientId 
       + "&grant_type=password" 
       + "&username=" + username 
       + "&password=" + password 
       + "&resource=" + encodeURIComponent(baseUrl); 

    return this.http.fetch(baseUrl + 'connect/token', { 
     method: 'post', 
     body : data 
    }); 
} 

sorgente completo può essere visto qui:

https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

Spero che questo aiuti,

migliore,

Alex

Problemi correlati