Hi @Moinuddin Mohamed ,
The issue is when logging in using the different authentication methods and the policy being checked for both when it should only be checked for one.
You can try to use AddPolicyScheme()
and ForwardDefaultSelector property to set the authentication scheme. Code like this:
builder.Services.AddAuthentication(options => // JwtBearerDefaults.AuthenticationScheme)
{
options.DefaultScheme = "JWT_OR_COOKIE";
options.DefaultChallengeScheme = "JWT_OR_COOKIE";
})
.AddCookie(options =>
{
options.LoginPath = "/login";
options.ExpireTimeSpan = TimeSpan.FromDays(1);
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "issuer",
ValidateAudience = true,
ValidAudience = "audience",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("signingkey"))
};
})
.AddPolicyScheme("JWT_OR_COOKIE", "JWT_OR_COOKIE", options =>
{
options.ForwardDefaultSelector = context =>
{
string authorization = context.Request.Headers[HeaderNames.Authorization];
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer "))
{
return JwtBearerDefaults.AuthenticationScheme;
}
return CookieAuthenticationDefaults.AuthenticationScheme;
};
});
Using the above code, the policy will run the JWT_OR_COOKIE scheme, and the JWT_OR_COOKIE scheme will forward select to the actual scheme based on the ForwardDefaultSelector delegate.
More detail information, refer to Combining Bearer Token and Cookie Authentication in ASP.NET and Multiple authentication schemes
Besides, I also find the following methods which might achieve the same behavior:
- Write a custom middleware that manually calls AuthenticateAsync() and creates a ClaimsPrincipal containing all the identities you need. See How do I setup multiple auth schemes in ASP.NET Core 2.0?
- Create a custom Authorization attribute, then check the authorization header (use cookie or token). Refer to Authorization mechanism which uses JWT token OR API-key in .NET Core
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion