asp.net 如何在API中验证自定义标记(不是JWT)?

vc6uscn9  于 2022-12-15  发布在  .NET
关注(0)|答案(2)|浏览(156)

在我们的API中,当用户登录时,我们生成一个GUID,并在将其存储到数据库后将其返回给用户。当用户向具有Authorize属性的控制器提交请求时,验证此令牌的最佳实践是什么?
我应该重写AuthorizeAttribute.OnAuthorization并将我的自定义逻辑放在那里吗?或者是否有任何其他地方我应该放置我的自定义逻辑?
先谢了。

e37o9pze

e37o9pze1#

在ASP.NETCore2.0中,你可以编写自己的中间件来验证令牌。你可以看到这个视频,例如:https://www.youtube.com/watch?v=n0llyujNGw8
总结:1.创建令牌中间件:

public class TokenMiddleware
{
    // always should be RequestDelegate in constructor
    private readonly RequestDelegate _next;
    public TokenMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // always should be defiened Invoke or InvokeAsync with HttpContext and returned Task (You can also inject you services here - for example DataContext)
    public async Task InvokeAsync(HttpContext context, DataContext dataContext)
    {
        var validKey = true;

        // than you logic to validate token              

        if (!validKey)
        {
            context.Response.StatusCode = (int) HttpStatusCode.Forbidden;
            await context.Response.WriteAsync("Invalid Token");
        }
        // if validm than next middleware Invoke
        else
        {
            await _next.Invoke(context);
        }
    }
}

// Extension to IApplicationBuilder (to register you Middleware)
public static class TokenExtensions
{
    public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<TokenMiddleware>();
    }
}

1.已在启动中注册中间件:
应用程序使用令牌验证();

cwdobuhd

cwdobuhd2#

问题很久以前就提出了,但是对于那些可能偶然发现它的人,我是这样做的,利用了身份验证和授权中间件。这个问题没有关于令牌在请求中传递方式的细节,但是我假设了一个标准的授权头。

创建自定义验证处理程序

  • 我的自定义令牌处理程序.cs*
public class MyCustomTokenHandler: AuthenticationHandler<AuthenticationSchemeOptions>
{
    public MyCustomTokenHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.ContainsKey("Authorization"))
        {
            return AuthenticateResult.NoResult();
        }
        if (!AuthenticationHeaderValue.TryParse(Request.Headers["Authorization"], out AuthenticationHeaderValue? headerValue))
        {
            return AuthenticateResult.NoResult();
        }
        if (!Scheme.Name.Equals(headerValue.Scheme, StringComparison.OrdinalIgnoreCase))
        {
            return AuthenticateResult.NoResult();
        }
        if (headerValue.Parameter == null)
        {
            return AuthenticateResult.NoResult();
        }
        //The token value is in headerValue.Parameter, call your db to verify it and get the user's data

        var claims = new[] { new Claim(ClaimTypes.Name, "username found in db") };
        //set more claims if you want
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);
        return AuthenticateResult.Success(ticket);
    }
}

注册处理程序并启用授权

  • 程序.cs*
builder.Services.AddAuthentication("Bearer").AddScheme<AuthenticationSchemeOptions, MyCustomTokenHandler>("Bearer", null);
//...
var app = builder. Build();
app.UseAuthentication();
app.UseAuthorization();

大部分代码的灵感来自这篇博客文章:https://joonasw.net/view/creating-auth-scheme-in-aspnet-core-2

相关问题