我需要结合令牌和 cookie 来授权 wepapi 项目中的请求。
我添加了 Cookie 和 Jwt 来验证请求。
在更改 DefaultPolicy 之前,我可以获得我的声明(/信息),但更改后我得到 401。
这是我的 Program.cs 代码:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://localhost:7208/";
options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
});
var multiSchemePolicy = new AuthorizationPolicyBuilder(
CookieAuthenticationDefaults.AuthenticationScheme,
JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
builder.Services.AddAuthorization(o =>
{
o.DefaultPolicy = multiSchemePolicy;
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
和控制器代码:
namespace Whois.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class AccountController : ControllerBase
{
[HttpGet("info")]
[Authorize]
public IActionResult Info()
{
return Ok(User.Claims.Select(m => m.Value));
}
[HttpPost("login")]
public async Task<IActionResult> Login()
{
var user = _userManager.Users.FirstOrDefault();
await _signInManager.SignInAsync(user, new AuthenticationProperties() { });
return Ok();
}
}
}
有什么解决办法吗?
问题是当您使用signInManager登录时,它会添加Identity.Application而不是cookie。
解决方案:
builder.Services.AddAuthentication()
.AddCookie()
.AddJwtBearer("Bearer", options => { });
var policy = new AuthorizationPolicyBuilder("Identity.Application", "Bearer")
.RequireAuthenticatedUser().Build();
builder.Services.AddAuthorization(m => m.DefaultPolicy = policy);
构建策略时,将 CookieAuthenticationDefaults.AuthenticationScheme 替换为 Identity.Application。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)