Blog.Core/Blog.Core.Gateway/Extensions/CustomAuthenticationHandler.cs

53 lines
1.8 KiB
C#
Raw Permalink Normal View History

2022-02-05 12:10:50 +08:00
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
2022-02-11 19:27:46 +08:00
namespace Blog.Core.Gateway.Extensions
2022-02-05 12:10:50 +08:00
{
2022-02-06 14:05:51 +08:00
public class CustomAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
2022-02-05 12:10:50 +08:00
{
2022-02-06 14:05:51 +08:00
public CustomAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
2022-02-05 12:10:50 +08:00
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
2022-02-06 14:05:51 +08:00
// 可以查询数据库等操作
// 获取当前用户不能放到token中的私密信息
var userPhone = "15010000000";
2022-02-05 12:10:50 +08:00
var claims = new List<Claim>()
{
2022-02-06 14:05:51 +08:00
new Claim("user-phone", userPhone),
new Claim("gw-sign", "gw")
2022-02-05 12:10:50 +08:00
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name));
var ticket = new AuthenticationTicket(principal, Scheme.Name);
await Task.CompletedTask;
return AuthenticateResult.Success(ticket);
}
protected virtual string GetTokenStringFromHeader()
{
var token = string.Empty;
string authorization = Request.Headers[HeaderNames.Authorization];
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith($"Bearer ", StringComparison.OrdinalIgnoreCase))
{
token = authorization["Bearer ".Length..].Trim();
}
return token;
}
}
}