ASP .NET Core 2.0中的多个身份验证方案

编程入门 行业动态 更新时间:2024-10-23 15:24:48
本文介绍了ASP .NET Core 2.0中的多个身份验证方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在 ASP.NET Core 2.0 MVC应用程序中支持两种身份验证类型:

I need to support two authentication types in ASP.NET Core 2.0 MVC application:

  • AddIdentityServerAuthentication
  • AddOpenIdConnect
  • 在 ASP.NET Core 1.0 版本中,这非常容易.但是在 2.0版版本中,语法已更改.这是我的代码:

    It was very easy in ASP.NET Core 1.0 version. But in version 2.0 version syntax changed. This is my code:

    services.AddAuthentication(o => { o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; o.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme; }).AddIdentityServerAuthentication(options => { options.Authority = PlatformConfiguration.IdentityServerUri; options.RequireHttpsMetadata = false; options.SaveToken = true; options.ApiSecret = "somesecret"; options.ApiName = "some_api"; }) .AddCookie() .AddOpenIdConnect(o => { o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; o.Authority = PlatformConfiguration.IdentityServerUri; o.RequireHttpsMetadata = false; o.ClientId = "some_viewer"; o.UseTokenLifetime = true; o.ResponseType = "id_token token"; o.Scope.Add("openid"); o.Scope.Add("roles"); o.Scope.Add("profile"); o.SaveTokens = true; o.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role }; }); services.AddAuthorization();

    但是以这种方式,承载身份验证不起作用.由于存在以下默认方案: DefaultChallengeScheme , DefaultAuthenticateScheme . 如何定义几种身份验证方案?

    But in this way, the Bearer authentication doesn't work. Because of default schemes: DefaultChallengeScheme, DefaultAuthenticateScheme. How to define several authentication schemes?

    推荐答案

    我添加了属性

    [Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme + "," + OpenIdConnectDefaults.AuthenticationScheme)]

    现在我有两种身份验证方案.

    And now I have two authentication schemes.

    在启动中使用此代码的更灵活的解决方案:

    More flexible solution to use this code in Startup:

    if (UseAuthorization) { var policy = new AuthorizationPolicyBuilder(IdentityServerAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }

    更多推荐

    ASP .NET Core 2.0中的多个身份验证方案

    本文发布于:2023-11-16 18:31:10,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1606758.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:多个   身份验证   方案   NET   ASP

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!