简体   繁体   中英

Unable to authorize with a specific scheme in ASP.NET Core 6.0

I am attempting to authorize with a specific scheme as described here .

In Program.cs I have the following code:

builder.Services.AddAuthentication()
.AddCookie("SchemeName", options =>
{
    options.LoginPath = "/identity/account/login";
});

...

app.UseAuthentication();
app.UseAuthorization();

In my controller, I add the Authorize attribute:

[Authorize(AuthenticationSchemes = "SchemeName")]

I am able to login, but when I try to access any of the controller actions, I am redirected to the login page as if I am not logged in. I verified that I am logged in though with the following code on the login page that displays "true":

User Authenticated: @User.Identity.IsAuthenticated

This is as basis as it gets, so I'm not sure what I am missing. I intentionally removed every extra option to rule out any of the extra options I will eventually add.

When I just use [Authorize] (remove "AuthenticationScheme"), I don't have the issue, but my goal is to setup an authentication scheme and use it.

If you don't use identity, you can add your defaultScheme like below:

builder.Services.AddAuthentication("SchemeName")
.AddCookie("SchemeName", options =>
{
    options.LoginPath = "/identity/account/login";
});

And use on your contoller:

[Authorize(AuthenticationSchemes = "SchemeName")]

When you use identity, you have AddDefaultIdentity , so the defaultScheme has been set already. As @Jeremy Lakeman has said, "If its the default scheme, you wouldn't need to specify it on the controller."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM