gpt4 book ai didi

asp.net-core - 在 ASP.Net Core 中覆盖 AuthorizeAttribute 并响应 Json 状态

转载 作者:行者123 更新时间:2023-12-04 16:33:26 26 4
gpt4 key购买 nike

我正在从 ASP.Net Framework 迁移到 ASP.Net Core。

在带有 Web API 2 项目的 ASP.Net Framework 中,我可以像这样自定义 AuthorizeAttribute:

public class ApiAuthorizeAttribute : AuthorizationFilterAttribute
{
#region Methods

/// <summary>
/// Override authorization event to do custom authorization.
/// </summary>
/// <param name="httpActionContext"></param>
public override void OnAuthorization(HttpActionContext httpActionContext)
{
// Retrieve email and password.
var accountEmail =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Email"))
.Select(x => x.Value.FirstOrDefault())
.FirstOrDefault();

// Retrieve account password.
var accountPassword =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Password"))
.Select(x => x.Value.FirstOrDefault()).FirstOrDefault();

// Account view model construction.
var filterAccountViewModel = new FilterAccountViewModel();
filterAccountViewModel.Email = accountEmail;
filterAccountViewModel.Password = accountPassword;
filterAccountViewModel.EmailComparision = TextComparision.Equal;
filterAccountViewModel.PasswordComparision = TextComparision.Equal;

// Find the account.
var account = RepositoryAccount.FindAccount(filterAccountViewModel);

// Account is not found.
if (account == null)
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

return;
}

// Role is not defined which means the request is allowed.
if (_roles == null)
return;

// Role is not allowed
if (!_roles.Any(x => x == account.Role))
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden);

return;
}

// Store the requester information in action argument.
httpActionContext.ActionArguments["Account"] = account;
}

#endregion

#region Properties

/// <summary>
/// Repository which provides function to access account database.
/// </summary>
public IRepositoryAccount RepositoryAccount { get; set; }

/// <summary>
/// Which role can be allowed to access server.
/// </summary>
private readonly byte[] _roles;

#endregion

#region Constructor

/// <summary>
/// Initialize instance with default settings.
/// </summary>
public ApiAuthorizeAttribute()
{
}

/// <summary>
/// Initialize instance with allowed role.
/// </summary>
/// <param name="roles"></param>
public ApiAuthorizeAttribute(byte[] roles)
{
_roles = roles;
}

#endregion
}

在我自定义的 AuthorizeAttribute 中,我可以检查帐户是否有效并将带有消息的 HttpStatusCode 返回给客户端。

我正在尝试在 ASP.Net Core 中做同样的事情,但没有 OnAuthorization 可供我覆盖。

如何实现与 ASP.Net Framework 中相同的功能?

谢谢,

最佳答案

您正在错误地处理这个问题。从未真正鼓励为此编写自定义属性或扩展现有属性。与 ASP.NET 核心 为了向后兼容,角色仍然是系统的一部分,但现在也不鼓励使用。

有一个很棒的 2 部分系列,介绍了一些驱动架构的变化,以及它的使用方式和应该使用的方式,发现 here .如果您仍想依赖角色,您可以这样做,但我建议您使用策略。

要连接策略,请执行以下操作:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy(nameof(Policy.Account),
policy => policy.Requirements.Add(new AccountRequirement()));
});

services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}

我创建了一个 Policy为方便起见枚举。

public enum Policy { Account };

像这样装饰入口点:

[
HttpPost,
Authorize(Policy = nameof(Policy.Account))
]
public async Task<IActionResult> PostSomething([FromRoute] blah)
{
}
AccountRequirement只是一个占位符,它需要实现 IAuthorizationRequirement界面。

public class AccountRequirement: IAuthorizationRequirement { }

现在我们只需要创建一个处理程序并将其连接到 DI。

public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{
// Your logic here... or anything else you need to do.
if (context.User.IsInRole("fooBar"))
{
// Call 'Succeed' to mark current requirement as passed
context.Succeed(requirement);
}

return Task.CompletedTask;
}
}

其他资源
  • ASP.NET Core Security -- All the things
  • 关于asp.net-core - 在 ASP.Net Core 中覆盖 AuthorizeAttribute 并响应 Json 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637504/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com