I\'m trying to do a really simple implementation of JWT bearer authentication with ASP.NET Core. I return a response from a controller a bit like this:
var i
With this solution, you can access the User.Identity
and its claims in controllers when you're using JWT tokens:
Step 1: create a JwtTokenMiddleware:
public static class JwtTokenMiddleware
{
public static IApplicationBuilder UseJwtTokenMiddleware(
this IApplicationBuilder app,
string schema = "Bearer")
{
return app.Use((async (ctx, next) =>
{
IIdentity identity = ctx.User.Identity;
if ((identity != null ? (!identity.IsAuthenticated ? 1 : 0) : 1) != 0)
{
AuthenticateResult authenticateResult = await ctx.AuthenticateAsync(schema);
if (authenticateResult.Succeeded && authenticateResult.Principal != null)
ctx.User = authenticateResult.Principal;
}
await next();
}));
}
}
Step 2: use it in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseJwtTokenMiddleware();
}