5

Ich arbeite durch einige Beispiele MVC 6 und ASP.NET 5, und ich habe Probleme, eine würdige Dokumentation über die Verwendung von Bearer Tokens zu finden, um APIs zu sichern. Ich bin in der Lage, solche Beispiele mit VS 2013, MVC 5 arbeiten zu lassen, aber ich kann diese nicht auf VS 2015 und MVC 6 portieren. Kennt jemand gute Beispiele für die Implementierung von Bearer Tokens in MVC 6, um APIs zu sichern?Wie verwende ich Bearer Token mit MVC 6 API?

+0

FYI, ASP.NET MVC 6 (als Teil von ASP.NET 5) doesn erstellen‘ Es gibt noch keine integrierte Unterstützung für Bearer Token, aber das ASP.NET-Team untersucht dies. – Eilon

+0

Ich vermutete so viel, danke für deine Antwort! –

Antwort

2

Um eine Anfrage mit Bearer Token zu authentifizieren, können Sie das Microsoft.AspNet.Security.OAuthBearer Paket herunterziehen. Sie können die OAuthBearerAuthenticationMiddleware Middleware dann zu der Pipeline hinzufügen, indem Sie die Erweiterungsmethode UseOAuthBearerAuthentication verwenden.

Beispiel:

public void Configure(IApplicationBuilder app) 
{ 

    // ... 

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

Außerdem haben Sie einen Blick auf WebApp-WebAPI-OpenIdConnect-AspNet5 Probe.

0

Ich habe eine Single-Page-Anwendung mit Token-basierte Authentifizierung Implementierung mit MVC 6, OpenId und Aurelia Front-End-Framework implementiert. In Startup.cs sucht die Configure-Methode wie folgt:

// 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?}"); 
    }); 
} 

Der Authentifizierungsanbieter wie so definiert ist:

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

Dies definiert einen Token-Endpunkt, der an der URL /connect/token erreicht werden kann.

So ein Token von der Client-Seite anzufordern, hier ist der JavaScript-Code, aus dem AuthService in authSvc.js genommen:

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

Vollquelle hier zu sehen ist:

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

hoffe, das hilft,

Best,

Alex

Verwandte Themen