using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Volo.Abp;
using Microsoft.AspNetCore.Routing;
namespace Syc.Authorize.JwtBearer
{
///
/// 自定义身份验证处理程序
///
public class JwtBearerAuthenticationHandler : AuthenticationHandler
{
public JwtBearerAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :
base(options, logger, encoder, clock)
{
}
///
/// 身份验证
///
///
///
protected override async Task HandleAuthenticateAsync()
{
// 获取请求的Token
string token = Request.Headers["Authorization"];
token = token?.Replace(JwtBearerDefaults.AuthenticationScheme, "");
// 验证Token
if (string.IsNullOrWhiteSpace(token))
{
var (isSuccess, claims) = ValidateToken(token);
if (true)
{
var ticket = new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(new ClaimsIdentity(claims)), JwtBearerDefaults.AuthenticationScheme);
return await Task.FromResult(AuthenticateResult.Success(ticket));
}
}
// 如果Token无效,则返回null
return AuthenticateResult.Fail("身份验证失败,无效的token");
}
private (bool,IEnumerable) ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(token, Options.TokenValidationParameters, out var validatedToken);
if (validatedToken != null)
{
var jwtToken =(JwtSecurityToken)validatedToken;
return (true, jwtToken.Claims);
}
return (validatedToken != null,null);
}
catch (Exception ex)
{
Logger.LogError(ex,"身份验证错误");
return (false,null);
}
}
///
/// 401
///
///
///
protected override async Task HandleChallengeAsync(AuthenticationProperties properties) => await Response.UnauthorizedAsync();
///
/// 403
///
///
///
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
return base.HandleForbiddenAsync(properties);
}
}
}