C# 在ASP.NET Core 3.1中使用多个身份验证方案?
我一直在使用ASP.NET Core 3.1和干净的体系结构制作一个web应用程序 我有一些类库,比如Infrastructure、Persistence、Domain、Application,还有一个名为“Web”的MVC应用程序项目作为我的应用程序的启动点 在Web层中,我有一个“区域”,其中有一个管理区域,包含一些控制器和操作方法,这些方法将JSON作为API端点返回,以便在基于React的应用程序中使用 我在controllers文件夹中的WebMVC项目中也有一些控制器,它们的操作方法返回html视图 我还将Identity和JWT用于API端点,但: -如果我想在其操作结果返回html视图的MVC控制器中使用基于声明的标识,该怎么办? -在此类应用程序中使用ASP.NET Core 3.1中基于声明的身份的最佳实践是什么?C# 在ASP.NET Core 3.1中使用多个身份验证方案?,c#,asp.net-mvc,asp.net-core,asp.net-web-api,identity,C#,Asp.net Mvc,Asp.net Core,Asp.net Web Api,Identity,我一直在使用ASP.NET Core 3.1和干净的体系结构制作一个web应用程序 我有一些类库,比如Infrastructure、Persistence、Domain、Application,还有一个名为“Web”的MVC应用程序项目作为我的应用程序的启动点 在Web层中,我有一个“区域”,其中有一个管理区域,包含一些控制器和操作方法,这些方法将JSON作为API端点返回,以便在基于React的应用程序中使用 我在controllers文件夹中的WebMVC项目中也有一些控制器,它们的操作方法
任何帮助都将不胜感激。在做了一些研究之后,我在ASP.NET核心授权文档中的一篇标题为“”的文章中找到了解决方案 根据Microsoft ASP.NET核心文档中提到的文章,在某些场景中,例如单页应用程序(SPA),通常使用多种身份验证方法。例如,应用程序可以使用基于cookie的身份验证登录,并使用JWT承载身份验证进行JavaScript请求 在身份验证期间配置身份验证服务时,将命名身份验证方案。例如:
public void ConfigureServices(IServiceCollection services)
{
// Code omitted for brevity
services.AddAuthentication()
.AddCookie(options => {
options.LoginPath = "/Account/Unauthorized/";
options.AccessDeniedPath = "/Account/Forbidden/";
})
.AddJwtBearer(options => {
options.Audience = "http://localhost:5001/";
options.Authority = "http://localhost:5000/";
});
在前面的代码中,添加了两个身份验证处理程序:一个用于cookie,一个用于承载
选择具有Authorize属性的方案
[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
public class MixedController : Controller
在前面的代码中,只有具有“Bearer”方案的处理程序运行。忽略任何基于cookie的标识
这是解决我的问题的解决方案,我想如果有需要,最好与大家分享。在.Net Core 3.1或.Net 5.0中有多种身份验证方案 Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.LoginPath = "/";
x.ExpireTimeSpan = TimeSpan.FromMinutes(Configuration.GetValue<int>("CookieExpiry"));
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JWTSecret"))),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme);
defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x=>
{
x、 LoginPath=“/”;
x、 ExpireTimeSpan=TimeSpan.FromMinutes(Configuration.GetValue(“CookieExpire”);
})
.AddJwtBearer(x=>
{
x、 RequireHttpsMetadata=false;
x、 SaveToken=true;
x、 TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetValue(“JWTSecret”)),
validateisuer=false,
ValidateAudience=false
};
});
services.AddAuthorization(选项=>
{
var defaultAuthorizationPolicyBuilder=新的AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme,JwtBearerDefaults.AuthenticationScheme);
defaultAuthorizationPolicyBuilder=defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
options.DefaultPolicy=defaultAuthorizationPolicyBuilder.Build();
});
/api/auth/login
public async Task<AuthenticationResult> Login([FromForm] string userName, [FromForm] string password, [FromHeader] string authmode = "")
{
if (userName != "demo" || password != "demo")
return new AuthenticationResult { HasError = true, Message = "Either the user name or password is incorrect." };
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, userName)
};
if(authmode?.ToLower() == "token")
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config.GetValue<string>("JWTSecret"));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims, "JWT"),
Expires = DateTime.UtcNow.AddMinutes(_config.GetValue<int>("JWTExpiry")),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);
return new AuthenticationResult { Token = jwt };
}
else
{
ClaimsPrincipal princ = new ClaimsPrincipal(new ClaimsIdentity(claims, "COOKIE"));
await HttpContext.SignInAsync(princ);
return new AuthenticationResult();
}
}
公共异步任务