简体   繁体   English

ASP.Net Core 的自定义承载令牌授权

[英]Custom Bearer Token Authorization for ASP.Net Core

Is this an acceptable implementation of a custom bearer token authorization mechanism?这是自定义不记名令牌授权机制的可接受实现吗?

Authorization Attribute授权属性

public class AuthorizeAttribute : TypeFilterAttribute
{
    public AuthorizeAttribute(): base(typeof(AuthorizeActionFilter)){}
}

public class AuthorizeActionFilter : IAsyncActionFilter
{
    private readonly IValidateBearerToken _authToken;
    public AuthorizeActionFilter(IValidateBearerToken authToken)
    {
        _authToken = authToken;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        const string AUTHKEY = "authorization";
        var headers = context.HttpContext.Request.Headers;
        if (headers.ContainsKey(AUTHKEY))
        {
            bool isAuthorized = _authToken.Validate(headers[AUTHKEY]);
            if (!isAuthorized)
                context.Result = new UnauthorizedResult();
            else
                await next();
        }
        else
            context.Result = new UnauthorizedResult();
    }
}

Validation Service.验证服务。 APISettings class is used in appSettings, but validation can be extended to use a database ... obviously :) APISettings 类在 appSettings 中使用,但验证可以扩展为使用数据库......显然:)

public class APISettings
{
    public string Key { get; set; }
}

public class ValidateBearerToken : IValidateBearerToken
{
    private readonly APISettings _bearer;

    public ValidateBearerToken(IOptions<APISettings> bearer)
    {
        _bearer = bearer.Value;
    }

    public bool Validate(string bearer)
    {
        return (bearer.Equals($"Bearer {_bearer.Key}"));
    }
}

Implementation实施

[Produces("application/json")]
[Route("api/my")]
[Authorize]
public class MyController : Controller

appSettings应用设置

"APISettings": {
"Key": "372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046"

} }

Request Header请求头

Authorization: Bearer 372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046

That would work, but it's kind of reinventing the wheel.这会奏效,但有点像重新发明轮子。

I good approach these days is to use JWTs, you can find more info about it here: http://www.jwt.io/这些天我的好方法是使用 JWT,您可以在此处找到有关它的更多信息: http ://www.jwt.io/

Some advantages are that it integrates quite nicely with asp.net core and you can also add some information to the token (username, role, etc).一些优点是它与 asp.net core 很好地集成,您还可以向令牌添加一些信息(用户名、角色等)。 That way, you don't even need to access the database for validation (if you want to).这样,您甚至不需要访问数据库进行验证(如果您愿意)。

Also, storing keys in appsettings file could lead to accidentally adding them to your source-code manager (security).此外,将密钥存储在 appsettings 文件中可能会导致意外将它们添加到您的源代码管理器(安全性)中。 You could use user secrets for local development (or disable the key when environment = dev) and environment variables for production.您可以将用户机密用于本地开发(或在 environment = dev 时禁用密钥)和用于生产的环境变量。

Here is one good example of how to use jwt with asp.net: https://jonhilton.net/2017/10/11/secure-your-asp.net-core-2.0-api-part-1-issuing-a-jwt/以下是如何在 asp.net 中使用 jwt 的一个很好的例子: https ://jonhilton.net/2017/10/11/secure-your-asp.net-core-2.0-api-part-1-issuing-a -jwt/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM