ilM*_*ion 4 c# authentication asp.net-core
我正在开发一个Web api核心2.0项目。
我需要支持两种授权类型:jwt和basic。
在我的ConfigureServices方法中,我添加了以下代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer((options) =>
{
options.Authority = $"...";
options.Audience = "...";
});
services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(credentials =>
Task.FromResult(
credentials.username == "username"
&& credentials.password == "password"));
Run Code Online (Sandbox Code Playgroud)
在我的Configure方法中,我添加了以下代码:
app.UseAuthentication();
app.UseMvc();
Run Code Online (Sandbox Code Playgroud)
最后,我在控制器上添加了AuthorizeAttribute:
[Authorize]
public class MioController : Controller
{ ... }
Run Code Online (Sandbox Code Playgroud)
实际上仅工作在ConfigureServices上指定的最后一次身份验证。
如何支持两种身份验证类型?谢谢
注意:我正在使用此NuGet包进行基本身份验证Bazinga.AspNetCore.Authentication.Basic。
尝试将您的身份验证服务添加到一个链中
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer((options) =>
{
options.Authority = $"...";
options.Audience = "...";
})
.AddBasicAuthentication(credentials =>
{
Task.FromResult(credentials.username == "username" && credentials.password == "password"));
}
Run Code Online (Sandbox Code Playgroud)
并且还AuthorizeAttribute可以指定要用来验证请求身份的方案
[Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3204 次 |
| 最近记录: |