ASP.Net Core的自定义承载令牌授权 [英] Custom Bearer Token Authorization for ASP.Net Core

查看:121
本文介绍了ASP.Net Core的自定义承载令牌授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是否是可接受的自定义承载令牌授权机制的实现?

Is this an acceptable implementation of a custom bearer token authorization mechanism?

授权属性

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();
    }
}

验证服务. 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}"));
    }
}

实施

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

appSettings

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

}

请求标头

Authorization: Bearer 372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046

推荐答案

这行得通,但这是在重新发明轮子.

That would work, but it's kind of reinventing the wheel.

这些天我最好的方法是使用JWT,您可以在这里找到有关它的更多信息: http://www .jwt.io/

I good approach these days is to use JWTs, you can find more info about it here: http://www.jwt.io/

一些优点是它与asp.net核心很好地集成在一起,并且您还可以向令牌添加一些信息(用户名,角色等).这样,您甚至不需要访问数据库进行验证(如果需要).

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). That way, you don't even need to access the database for validation (if you want to).

此外,将密钥存储在appsettings文件中可能会导致将它们意外添加到源代码管理器中(安全性).您可以将用户机密用于本地开发(或在environment = dev时禁用密钥),并使用环境变量进行生产.

Also, storing keys in appsettings file could lead to accidentally adding them to your source-code manager (security). You could use user secrets for local development (or disable the key when environment = dev) and environment variables for production.

这里是如何在asp.net中使用jwt的一个很好的例子:

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 Core的自定义承载令牌授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆