【问题标题】:Using ASP.NET Core Identity for authenticating Controller usage使用 ASP.NET Core Identity 验证控制器的使用
【发布时间】:2021-07-04 17:27:31
【问题描述】:

我一直在开发一个 asp.net core razor 应用程序,我一直坚持使用视图和模型。但是,我添加了一个前端框架,因此经常使用 HTTP 请求,所以我想我会通过添加控制器来测试 asp.net 核心中的 Web API,将可用的 json 数组传递到前端是多么容易.我的问题是我在我的 razor 应用程序的 startup.cs 中实现了以下代码,以限制任何未登录的用户访问任何其他页面或页面模型,除非已登录:

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(cookieOptions => {
                cookieOptions.Cookie.Name = "UserLoginCookie";
                cookieOptions.LoginPath = "/Login/";
                cookieOptions.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                cookieOptions.SlidingExpiration = true;
            });

这很好用,除了我发现的问题是即使我没有登录我的测试 HomeController 仍然可以访问(url/home/index)。有没有办法使用我用于剃须刀页面的身份验证来限制仅登录用户访问控制器。此外,为了增加一层安全性,我想为登录用户的 ID 存储一个变量服务器端,并将其集成到控制器中,这样我就可以将我的查询限制在该用户,而不会让它成为一个 HTTP 参数,这样任何人都可以访问其他用户数据。

【问题讨论】:

    标签: asp.net-core asp.net-web-api asp.net-core-mvc razor-pages asp.net-core-3.1


    【解决方案1】:

    在 homecontroller 类上方添加 [Authorize] 可以解决问题,但不知道为什么我需要使用此标签才能使其工作。

    【讨论】:

      【解决方案2】:

      如果您在整个控制器上添加 [Authorize],它将阻止该类中的所有方法可访问。需要指定的授权 在这种情况下,CookieAuthenticationDefaults。 如果您有多个,则可以指定要检查的策略的名称

      [Authorize(Roles = "Administrator")]
      

      这里是 AuthorizeAttribute 类以获得更多信息

      using System;
      namespace Microsoft.AspNetCore.Authorization
      {
      /// <summary>
      /// Specifies that the class or method that this attribute is applied to requires the 
          specified authorization.
       /// </summary>
      [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple =true,  
        Inherited = true)]
      public class AuthorizeAttribute : Attribute, IAuthorizeData
      {
          /// <summary>
          /// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class with 
              the specified policy. 
          /// </summary>
          /// <param name="policy">The name of the policy to require for authorization.</param>
          public AuthorizeAttribute(string policy)
          {
              Policy = policy;
          }
      
          /// <summary>
          /// Gets or sets the policy name that determines access to the resource.
          /// </summary>
          public string? Policy { get; set; }
      
          /// <summary>
          /// Gets or sets a comma delimited list of roles that are allowed to access the resource.
          /// </summary>
          public string? Roles { get; set; }
      
          /// <summary>
          /// Gets or sets a comma delimited list of schemes from which user information is constructed.
          /// </summary>
          public string? AuthenticationSchemes { get; set; }
      }
      

      }

      【讨论】:

        最近更新 更多