5

Pracuję przez niektóre próbki MVC 6 i ASP.NET 5 i mam problemy ze znalezieniem jakiejkolwiek wartościowej dokumentacji na temat używania tokenów na okaziciela w celu zabezpieczenia interfejsów API. Mogę sprawić, aby takie próbki działały z VS 2013, MVC 5, ale nie jestem w stanie przenieść ich na VS 2015 i MVC 6. Czy ktoś wie o dobrych próbkach implementacji tokenów na okaziciela w MVC 6 w celu zabezpieczenia API?Jak używać tokenów na okaziciela z MVC 6 API?

+0

FYI, ASP.NET MVC 6 (jako część ASP.NET 5) robi” t mają wbudowane wsparcie dla tokenów okaziciela, ale zespół ASP.NET zajmuje się tym zagadnieniem. – Eilon

+0

Podejrzewałem tak samo, dziękuję za odpowiedź! –

Odpowiedz

2

Aby uwierzytelnić żądanie za pomocą tokenów na okaziciela, można usunąć pakiet Microsoft.AspNet.Security.OAuthBearer. Następnie można dodać oprogramowanie pośrednie OAuthBearerAuthenticationMiddleware do potoku za pomocą metody rozszerzenia UseOAuthBearerAuthentication.

przykład:

public void Configure(IApplicationBuilder app) 
{ 

    // ... 

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

również spojrzeć WebApp-WebAPI-OpenIdConnect-AspNet5 próbki.

0

Zaimplementowałem aplikację do obsługi pojedynczej strony z implementacją uwierzytelniania opartą na tokenach przy użyciu MVC 6, OpenId i Aurelia front end framework. W Startup.cs metoda Konfiguracja wygląda tak:

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

Dostawca uwierzytelniania jest zdefiniowane tak:

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

Definiuje symboliczny punkt końcowy, który może być osiągnięty przy url /connect/token.

więc zwrócić token od strony klienta, tutaj jest kod javascript, zaczerpnięte z AuthService w 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 
    }); 
} 

Pełna źródło można zobaczyć tutaj:

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

Nadzieja to pomaga,

Best,

Alex