Using both Cookie Authentication Middleware and JWT Authentication Middleware. When I sign in the user I create custom Claims and attach those to the cookie based identity. I also get a jwt token from an external source, and that has its own claims (I use this token to access external resources). My controller class looks something like this when enabling Authentication
[Authorize(AuthenticationSchemes = AuthSchemes)]
public class MixedController : Controller
// Requires the following imports:
// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Authentication.JwtBearer;
private const string AuthSchemes =
CookieAuthenticationDefaults.AuthenticationScheme + "," +
JwtBearerDefaults.AuthenticationScheme;
Based on the code snippet above, if either, Cookie or JWT auth is successful the request is deemed Authenticated. My requirement is to reject the request if either Cookie Auth or JWT auth fails. Using just one schema is not a good option for my case. If my cookie is valid but my token has expired I would like to fail the request on grounds of "not being authenticated". How can I do that?
Use policy based authentication. There you can check if current ClaimsPrincipal
(context.User
) has 2 Identities
, 1 from each successfully passed authentication scheme. Configure policy
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAllSchemes", policy =>
{
policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.RequireAssertion(context =>
{
return context.User.Identities.Count() == 2;
});
});
});
Specify authorization policy for controller
[Authorize(Policy = "RequireAllSchemes")]
public class MixedController : Controller
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With