我正在尝试配置我的 ASP.NET Core 7 Web API 以使用 ASP.NET Core Identity 作为用户/角色后端并使用 JwtBearer 作为授权方法。
这是我在
Program.cs
文件中的服务配置:
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.Password.RequiredLength = 10;
options.Password.RequireDigit = true;
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ZhuPalDbContext>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = jwtSetting.ValidAudience,
ValidIssuer = jwtSetting.ValidIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Secret))
};
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
当我尝试使用从登录端点检索的 JwtToken 调用标有
[Authorize]
的 Web API 操作方法时,我收到 http 404 响应代码。
查看我的 HTTP 客户端(Postman/Insomnia)后,我发现我被重定向到
Account/Login
页面,之后由于缺少重定向页面服务器,向客户端返回了 404 错误。
这是整个客户端日志:
Preparing request to http://localhost:5158/Profile/extra-data
* Current time is 2023-09-18T16:23:46.327Z
* Enable automatic URL encoding
* Using default HTTP version
* Enable timeout of 100000ms
* Enable SSL validation
* Enable cookie sending with jar of 25 cookies
* Found bundle for host localhost: 0x60c037228e0 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#19) with host localhost
* Connected to localhost (127.0.0.1) port 5158 (#19)
> POST /Profile/extra-data HTTP/1.1
> Host: localhost:5158
> User-Agent: insomnia/2023.3.0
> Cookie: oc6a5ui45zxj=l3dlncv9e1unk3756a0mfpm3la; ocqwk92njrjy=u3p42et9pvi3s84asbni3j2fh8; ocbms528iyn8=4ev2l2617v2eqhjdqlgehl7jm9; ocdrufwwtp37=sbiaak1e2knc48vslao2teqggs; ocge53hr7oxy=pnp681o4o509gc1ek909r0ocpt; ocozidua8aza=5tm1g0s70v69efhtcv8vvuvofh; ochrgckw3sfb=db1q3apkm7g34u5cqrlg7qtjql; ocw0k0k41r51=4q8g84fqi3s0jg4kc932jr5su0; ocg8vzbai0el=e4q8j7882pdmpalh93487jhic1; ocp6kao2et7b=etpk6f1tgvpgbaup7mlpjhtuvb; ock9akyrf9an=phh7r315quuejt0nve2smtpa1n; oc9f2lksuaal=1pofgkelnpj2o72r3nq3cnoqte; ocxougkoe4sh=hu5ve2k0i03jvoobct7h7gapfk; oci50bcnk8nq=gjjhcavr17mcff3vadvjdn47uk; ocp9eud6ezkt=u2b56ls1bpt8d57vcloe1c6q0m; ocvzvyc9ti1g=3ke8v4tvguika5b618elqodovu
> accept: */*
> Content-Type: application/json
> Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInNpZCI6IjAyMTc0Y2Yw4oCTOTQxMuKAkzRjZmUtYWZiZi01OWY3MDZkNzJjZjYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTY5NTA1NDIwMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0MjAwIn0.ev3ZqESXprt-6Tu2kO__dG1cb69N0cADCzyFw_4UDGU
> Content-Length: 177
| {
| "profileId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
| "extraData": {
| "additionalProp1": "string",
| "additionalProp2": "string",
| "additionalProp3": "string"
| }
| }
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Content-Length: 0
< Date: Mon, 18 Sep 2023 16:23:45 GMT
< Server: Kestrel
< Location: http://localhost:5158/Account/Login?ReturnUrl=%2FProfile%2Fextra-data
* Connection #19 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5158/Account/Login?ReturnUrl=%2FProfile%2Fextra-data'
* Switch from POST to GET
* Found bundle for host localhost: 0x60c037228e0 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#19) with host localhost
* Connected to localhost (127.0.0.1) port 5158 (#19)
> GET /Account/Login?ReturnUrl=%2FProfile%2Fextra-data HTTP/1.1
> Host: localhost:5158
> User-Agent: insomnia/2023.3.0
> Cookie: oc6a5ui45zxj=l3dlncv9e1unk3756a0mfpm3la; ocqwk92njrjy=u3p42et9pvi3s84asbni3j2fh8; ocbms528iyn8=4ev2l2617v2eqhjdqlgehl7jm9; ocdrufwwtp37=sbiaak1e2knc48vslao2teqggs; ocge53hr7oxy=pnp681o4o509gc1ek909r0ocpt; ocozidua8aza=5tm1g0s70v69efhtcv8vvuvofh; ochrgckw3sfb=db1q3apkm7g34u5cqrlg7qtjql; ocw0k0k41r51=4q8g84fqi3s0jg4kc932jr5su0; ocg8vzbai0el=e4q8j7882pdmpalh93487jhic1; ocp6kao2et7b=etpk6f1tgvpgbaup7mlpjhtuvb; ock9akyrf9an=phh7r315quuejt0nve2smtpa1n; oc9f2lksuaal=1pofgkelnpj2o72r3nq3cnoqte; ocxougkoe4sh=hu5ve2k0i03jvoobct7h7gapfk; oci50bcnk8nq=gjjhcavr17mcff3vadvjdn47uk; ocp9eud6ezkt=u2b56ls1bpt8d57vcloe1c6q0m; ocvzvyc9ti1g=3ke8v4tvguika5b618elqodovu
> accept: */*
> Content-Type: application/json
> Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInNpZCI6IjAyMTc0Y2Yw4oCTOTQxMuKAkzRjZmUtYWZiZi01OWY3MDZkNzJjZjYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJhZG1pbiIsImV4cCI6MTY5NTA1NDIwMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0MjAwIn0.ev3ZqESXprt-6Tu2kO__dG1cb69N0cADCzyFw_4UDGU
* Mark bundle as not supporting multiuse
< HTTP/1.1 404 Not Found
< Content-Length: 0
< Date: Mon, 18 Sep 2023 16:23:45 GMT
< Server: Kestrel
* Connection #19 to host localhost left intact
我的问题是:
Authorization
标头?如果您想让“asp.net core Identity”或“jwt”中的任何一个通过身份验证来请求api,您可以添加以下策略配置。
//Add a policy called "Jwt_Or_Identity" to allow either jwt or Identity.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Jwt_Or_Identity", policy =>
{
policy.AuthenticationSchemes.Add(IdentityConstants.ApplicationScheme);
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
在控制器或操作顶部设置
[Authorize()]
属性。
[Authorize(Policy = "Jwt_Or_Cookie")]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{...}
(您可以查看
AddIdentity
的源代码来确认它的方案名称是IdentityConstants.ApplicationScheme
)
关于重定向到
Account\login
的说明:您已添加
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>
,但页面未生成。 Account/Login
是此方法的默认登录页面。当没有用户登录时,请求将导致重定向到登录页面。Account/login
页面并添加(您需要在此处填写ApplicationUser
ZhuPalDbContext
以获取上下文和用户)