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?
risposta
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.
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
Non c'è alcun middleware in Asp.Net Core, che genera token bearer. È possibile creare il own solution o attuare alcune comunità come approcci basati
- 1. Come vengono creati i token bearer (OAuth2)?
- 2. MVC 6: come utilizzare i file RESX?
- 3. Come memorizzare i token bearer quando MVC e Web API si trovano in diversi progetti
- 4. Autorizzazione con token bearer OAuth fornito da API Web esterna
- 5. Autenticazione token bearer in ASP.NET Core
- 6. Cosa sono i token bearer e token_type in OAuth 2?
- 7. Personalizza token Bearer token Risultato JSON in ASP.NET WebApi 2
- 8. Identità ASP.NET + token bearer + multi-tenant
- 9. Token Web JSON sicuro in Web API/MVC 6
- 10. Web Api 2 Preflight richiesta CORS per token bearer
- 11. Come utilizzare Entity Framework 6.x in Asp.Net 5 (MVC 6)
- 12. Come continuare a utilizzare ModelState con RedirectToAction in ASP.NET MVC 6?
- 13. Babele 6 CLI: esportazione di token inaspettati?
- 14. AsyncController mancante in MVC 6
- 15. È possibile utilizzare asp.net mvc 6 in Visual Studio 2013?
- 16. GetOwinContext in MVC 6
- 17. Come utilizzare il token di aggiornamento per ottenere un nuovo token di accesso (django-oauth-toolkit)?
- 18. MVC 6 HttpPostedFileBase?
- 19. Come abilitare SSL nell'applicazione MVC 6?
- 20. Come registrare un filtro globale con mvc 6, asp.net 5
- 21. Autenticazione API Web Basic vs Bearer
- 22. MVC 6 Tag Helpers Intellisense?
- 23. Come posso utilizzare Backbone.js con ASP.Net MVC?
- 24. MVC 6 404 non trovato
- 25. babel 6 async/attendi: token imprevisto
- 26. Token del portlet API Web: posso utilizzare token personalizzati?
- 27. Come utilizzare l'autenticazione http in oggetto con un token omniauth opzionale come token di autenticazione
- 28. I token anti-contraffazione ASP.NET MVC CSRF scadono?
- 29. Fabbrica controller ASP.NET MVC 6
- 30. ASP.Net MVC 5 6, come utilizzare Error.cshtml condivisa come risposta di errore predefinito
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
Ho sospettato tanto, grazie per la tua risposta! –