在ASP.NET Core 3.1中使用多种身份验证方案?

时间:2020-06-11 10:58:02

标签: c# asp.net-mvc asp.net-core asp.net-web-api identity

我一直在使用干净的体系结构使用ASP.NET Core 3.1制作Web应用程序。

我有一些类库,例如基础结构,持久性,域,应用程序和一个名为“ Web”的MVC应用程序项目,作为我应用程序的启动点。

在Web层中,我具有“区域”,其中有一个管理区域,其中包含一些控制器和操作方法,这些操作方法将JSON作为我的API端点返回,以便在基于React的应用程序中使用。< / p>

我在Web MVC项目的Controllers文件夹中也有一些控制器,它们的 action方法返回html视图

我也将Identity和JWT用于我的API端点,但是:

-如果我想在我的MVC控制器中使用基于声明的身份,其操作结果将返回html视图怎么办?

-在此类应用程序中使用ASP.NET Core 3.1中基于声明的身份的最佳实践是什么?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

经过研究,我在标题为“ {Authorize with a specific scheme in ASP.NET Core”的文章中找到了ASP.NET核心授权文档中的解决方案。

基于Microsoft ASP .NET核心文档中提到的文章,在某些情况下,例如单页应用程序(SPA),通常使用多种身份验证方法。例如,该应用可能使用基于cookie的身份验证来登录,并针对JavaScript请求使用JWT承载身份验证。

在身份验证期间配置身份验证服务时,将命名身份验证方案。例如:

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的身份都会被忽略。

这是解决了我的问题的解决方案,我认为最好与需要这些的人分享。

答案 1 :(得分:3)

.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();
            });

/ 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();
    }
}

输出:

enter image description here enter image description here

enter image description here enter image description here