2016-06-08 45 views
11

Tentativo di utilizzare l'autenticazione basata su token bearer in un semplice progetto API Web Core. Ecco il mio Startup.csAutenticazione token bearer in ASP.NET Core

app.UseMvc(); 
//--- 
const string secretKey = "mysupersecret_secretkey!123"; 
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); 
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); 
//--- 
const string audience = "Audience"; 
const string issuer = "Issuer"; 
//--- 
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters 
{ 
    ValidateIssuerSigningKey = true, 
    IssuerSigningKey = signingKey, 

    ValidateIssuer = false, 
    ValidIssuer = issuer, 

    ValidateAudience = true, 
    ValidAudience = audience, 

    ValidateLifetime = true, 

    ClockSkew = TimeSpan.Zero, 
    AuthenticationType = JwtBearerDefaults.AuthenticationScheme 
}; 
//--- 
app.UseJwtBearerAuthentication(new JwtBearerOptions 
{ 
    AutomaticAuthenticate = true, 
    AutomaticChallenge = true, 
    TokenValidationParameters = tokenValidationParameters, 
    AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme, 
}); 

Inoltre aggiungo AuthorizeAttribute all'azione controllori

[HttpGet] 
[Authorize(ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 
public IEnumerable<string> Get() 
{ 
    return new[] { "value1", "value2" }; 
} 

Ma quando tenta di inviare richiesta GET con l'intestazione Authorization: Bearer [TOKEN] ottengo eccezione

System.InvalidOperationException: No authentication handler is configured to authenticate for the scheme: Bearer 
    at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager. 

Allora, qual è questo 'gestore di autenticazione'? Dove devo impostare questo gestore?

+0

Potete per favore condividere l'intero metodo 'configure'? – Pinpoint

+0

Shure, http://pastebin.com/TgRkHNZk app.UseSimpleTokenProvider - è una semplice registrazione Token Endpoint, ho trovato qui: https://github.com/nbarbettini/SimpleTokenProvider – Maxim

risposta

24

In ASP.NET Core, l'ordine del middleware è importante: vengono eseguiti nello stesso ordine in cui sono registrati. Qui, app.UseMvc() viene chiamato prima del middleware del portatore JWT, quindi questo non può funzionare.

Mettere app.UseMvc() alla fine della pipeline e dovrebbe funzionare:

app.UseJwtBearerAuthentication(new JwtBearerOptions 
{ 
    AutomaticAuthenticate = true, 
    AutomaticChallenge = true, 
    TokenValidationParameters = tokenValidationParameters, 
    AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme, 
}); 

app.UseMvc(); 
+1

Grazie mille! – Maxim