【问题标题】:Identity in MVC and JWT + Identity for API part of the applicationMVC 中的身份和 JWT + 应用程序 API 部分的身份
【发布时间】:2021-05-06 03:10:35
【问题描述】:

我得到了 .NET 5 Web 应用程序(MVC = 模型视图控制器),在这里我添加了带角色的 DefaultIdentity。我向角色添加了一个用户,我为控制器的授权和特定角色的方法创建了一个属性,它可以工作,这部分工作正常,例如[授权(角色=管理员)]

现在我已经添加了 API 控制器。我想在 API 控制器上使用相同的属性,但是这次用户将通过 API 登录到系统,并获取 JWT,并且 JWT 包含特定角色,这不是问题它也可以工作!

但问题在于将这两者放在一起工作!

在向 ConfigureServices 方法添加逻辑后,我无法再访问 MVC 控制器,而 API 控制器正在工作。我的意思是返回401,很明显我覆盖了规则,但我想保留两者,欢迎任何提示或解决方案!

services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
                .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = true,
                        ValidIssuer = appSettings.Issuer,
                        ValidateAudience = true,
                        ValidAudience = appSettings.Issuer,
                        ValidateLifetime = true
                    };
                });

【问题讨论】:

  • not able to access MVC controllers anymore 配置了默认身份验证方案 JwtBearerDefaults.AuthenticationScheme,这会导致问题。
  • 嗨@JS,关于这个案例的任何更新?

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


【解决方案1】:

我有类似的问题,不记得到底是什么,但我确定这是在 startup.cs 中添加身份验证的顺序 我的设置如下:

app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy();
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<IdentityContext>();

services.AddAuthentication()
              .AddCookie(cfg => cfg.SlidingExpiration = true)
              .AddJwtBearer(cfg =>
              {
                  cfg.RequireHttpsMetadata = false;
                  cfg.SaveToken = true;
                  cfg.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidIssuer = Configuration["Tokens:Issuer"],
                      ValidAudience = Configuration["Tokens:Issuer"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                  };
              });
        

【讨论】:

    【解决方案2】:

    我认为您的身份验证工作正常,但需要将 authorization 添加到您的启动服务和您的 api 控制器。在 .Net Core 5(或者我使用的是 3.1)中,将类似这样的内容添加到您的启动服务中:

    // can save "UserCredentials" as a public constant, to re-use in api
    services.AddAuthorization(options =>
    {
        options.AddPolicy("UserCredentials", policy =>
        {
            policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
            // add additional policies
        });
    });
    

    然后在您的 api 控制器中,引用新的“UserCredentials”策略:

    [HttpPost("Post")]
    [Authorize(Policy = "UserCredentials")]
    public async Task<ActionResult> Post()
    { 
    
    }
    

    【讨论】:

      【解决方案3】:

      在向 ConfigureServices 方法添加逻辑后,我无法再访问 MVC 控制器,而 API 控制器正在工作。

      在您的代码中,我们可以发现您将JwtBearerDefaults.AuthenticationScheme 配置为默认身份验证方案,这导致了问题。

      为了使您的 MVC 和 API 都能正常工作,您可以尝试从 AddAuthentication 方法中删除 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;。然后通过在 API 操作上应用 [Authorize] 属性来使用 specify the authentication scheme or schemes,如下所示。

      [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
      [HttpGet]
      public IActionResult GetAll()
      {
      

      【讨论】:

        猜你喜欢
        • 2019-06-30
        • 2017-10-29
        • 2019-10-30
        • 2015-04-04
        • 2016-01-16
        • 1970-01-01
        • 2016-02-21
        • 2015-09-05
        • 2019-11-21
        相关资源
        最近更新 更多