【问题标题】:Authorize user based on API-key supplied in request header in ASP.NET Core根据 ASP.NET Core 请求标头中提供的 API 密钥授权用户
【发布时间】:2017-06-23 12:25:30
【问题描述】:

我正在尝试在 ASP.NET Core 中重写我目前对 ASP.NET 4.6 的一些授权。

我知道授权发生了一些变化,我发现很难在 ASP.NET Core 中实现我非常简单的身份验证策略。

我的要求:

对服务器的每个请求都应包含一个名为“key”的标头。根据该键的值,我将能够查询数据库并检查该键是代表普通用户还是管理员用户。如果请求不包含有效的密钥,则该请求未被授权。

如何在 ASP.NET Core 中实现这一点?我发现的每个示例似乎都完全超出了我的需求。

在 ASP.NET 4.6 中,我使用自己的自定义 AuthorizeAttributes 在控制器上使用,例如

[User]
public IHttpActionResult DoSomethingOnlyUsersCanDo() {}

[Admin]
public IHttpActionResult DoSomethingOnlyAdminsCanDo() {}

我可以在 ASP.NET Core 中做同样的事情吗?

【问题讨论】:

    标签: asp.net-core authorization asp.net-authorization asp.net-core-identity


    【解决方案1】:

    在 ASP.NET Core 中,建议您不要从 AuthorizeAttribute 继承。相反,您可以制定自定义授权策略:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims

    您将需要一个身份验证处理程序,该处理程序根据标头为用户创建一个 ClaimsIdentity。然后,您可以制定政策来断言用户存在某些声明。

    您可以在此处找到基本身份验证的实现:https://github.com/blowdart/idunno.Authentication。 当然请注意 Barry 的评论:

    它旨在演示如何编写身份验证中间件,而不是您会认真考虑使用的东西。

    它的核心在BasicAuthenticationHandler,继承自AuthenticationHandler<BasicAuthenticationOptions>

    此实现中的主体是在开发人员制作的事件回调中创建的,在示例中为here

    if (context.Username == context.Password)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
            new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
        };
    
        context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
        context.Success();
    }
    

    然后根据主体调用此回调后,在处理程序中创建身份验证票:

    var ticket = new AuthenticationTicket(validateCredentialsContext.Principal, Scheme.Name);
    return AuthenticateResult.Success(ticket);
    

    我还写了一篇关于实现自定义身份验证方案的文章:Creating an authentication scheme in ASP.NET Core 2.0

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2015-04-02
      • 2020-02-19
      • 2021-04-17
      相关资源
      最近更新 更多