Reputation: 699
I am new to .net Core, I am trying to upgrade a project from .net Core 1.0 to 2.0, when I am trying to access the API I am getting this error. "no authentication handler is configured to authenticate for the scheme: "bearer" .net core 2.0". As UseJwtBearerAuthentication doesnt work in .net core 2.0 I replacing it with AddAuthentication.
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
var tvp = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = "ABC",
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = "User",
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here:
ClockSkew = TimeSpan.FromMinutes(5)
};
services.AddSingleton(s => tvp);
ConfigureAuth(services, tvp);
}
private void ConfigureAuth(IServiceCollection services, TokenValidationParameters tvp)
{
//TODO: Change events to log something helpful somewhere
var jwtEvents = new JwtBearerEvents();
jwtEvents.OnAuthenticationFailed = context =>
{
Debug.WriteLine("JWT Authentication failed.");
return Task.WhenAll();
};
jwtEvents.OnChallenge = context =>
{
Debug.WriteLine("JWT Authentication challenged.");
return Task.WhenAll();
};
jwtEvents.OnMessageReceived = context =>
{
Debug.WriteLine("JWT Message received.");
return Task.WhenAll();
};
jwtEvents.OnTokenValidated = context =>
{
Debug.WriteLine("JWT Message Token validated.");
return Task.WhenAll();
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = tvp;
o.Events = jwtEvents; });
}
Under Configure method I have:
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseRequestResponseLogging();
app.UseNoCacheCacheControl();
app.UseMvc();
AuthController.cs
[HttpPost]
[EnableCors("AllowAll")]
[AllowAnonymous]
[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Authenticate([FromBody] UserContract model)
{
}
AuthenticationMiddleware:
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IAuthUser authUser)
{
if (context.User?.Identity != null)
{
if (context.User?.Identity?.IsAuthenticated == true)
{
authUser.Username = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
}
using (LogContext.PushProperty("Username", authUser.Username))
{
await _next.Invoke(context);
}
}
}
Upvotes: 0
Views: 910
Reputation: 27528
You can use AddJwtBearer method , please refer to below article for how to use extension :
https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide
Code sample below for AddJwtBearer with options and events is for your reference :
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("Bearer",options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Issuer",
ValidAudience = "Audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Yourkey"))
};
options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
var loggerFactory = context.HttpContext.RequestServices
.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Startup");
logger.LogInformation("Token-Expired");
context.Response.Headers.Add("Token-Expired", "true");
}
return System.Threading.Tasks.Task.CompletedTask;
},
OnMessageReceived = (context) =>
{
return Task.FromResult(0);
}
};
});
And use on controller/action like :
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Don't forget to enable authentication in Configure
method :
app.UseAuthentication();
Upvotes: 1