使用ASP.用于验证控制器使用情况的NET核心标识



我一直在开发一个asp.net核心的剃刀应用程序,我一直坚持使用视图和模型。然而,我添加了一个前端框架,所以经常使用HTTP请求,所以我想通过添加一个控制器来测试asp.net核心中的Web API,将可用的json数组传递到前端是多么容易,真是太棒了。我的问题是,我在我的剃须刀应用程序的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参数,这样任何人都可以访问其他用户的数据。

在homecontroller类上方添加[Authorize]确实奏效了,但不确定为什么需要使用此标记才能使其工作。

如果在整个控制器上添加[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; }
}

}

相关内容

最新更新