I am building an ASP.NET Core 2.2 Web API project that also serves up Razor pages. My plan is to have users authenticate using a Razor page, but also provide secure Web API endpoints for use with AJAX calls. I have implemented JWT Authorization for the Web API, and hoped to use JWT Authentication for the Razor pages as well. The problem is that I can't find any examples of using JWT with Razor pages. Others have asked similar questions, but with no real answers (ASP.NET Core 2.2 JWT Authentication).
I added this to ConfigureServices to configure Jwt:
services.AddScoped<JwtAuthenticationEvents>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Jwt";
options.DefaultChallengeScheme = "Jwt";
}).AddJwtBearer("Jwt", options =>
{
options.EventsType = typeof(JwtAuthenticationEvents);
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
}).AddCookie("Bearer", options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
And created a new JwtAuthenticationEvents class, similar to what I have done with Cookie Validation:
public class JwtAuthenticationEvents : JwtBearerEvents
{
private readonly IRepo _repo;
public JwtAuthenticationEvents(IRepo repo)
{
_repo = repo;
}
public override async Task Challenge(JwtBearerChallengeContext context)
{
var userPrincipal = context;
}
public override async Task MessageReceived(MessageReceivedContext context)
{
var userPrincipal = context.Principal;
}
public override async Task TokenValidated(TokenValidatedContext context)
{
var userPrincipal = context.Principal;
...
}
}
The JwtAuthenticationEvents class seems to be working, with the Challenge method being hit when I load a page with the [Authorize] attribute, but then I just get a 401 error. I am trying to figure out how to redirect to the Login form so I can create a token. Going directly to Login also gives a 401. I'm not sure where to go from here.
Any thoughts on this? Is there a better way to accomplish what I am trying to do?