60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
using Microsoft.AspNetCore.Mvc.Authorization;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
|
|
namespace Falcon.SugarApi.JWT
|
|
{
|
|
/// <summary>
|
|
/// 验证
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class ApiAuthorizationAttribute : Attribute, IAuthorizationFilter
|
|
{
|
|
/// <summary>
|
|
/// 用户需要具有的角色
|
|
/// </summary>
|
|
public List<string> Roles { get; set; } = new List<string>();
|
|
|
|
/// <inheritdoc/>
|
|
public void OnAuthorization(AuthorizationFilterContext context) {
|
|
if (context.Filters.Any(f => f is IAllowAnonymousFilter)) {
|
|
return;
|
|
}
|
|
var option = context.HttpContext.RequestServices.GetRequiredService<JwtContext>();
|
|
var key = option?.AuthHeaderKey;
|
|
key.ThrowNullExceptionWhenNull();
|
|
var token = context.HttpContext.Request.Headers[key].ToString();
|
|
if (token.IsNullOrEmpty()) {
|
|
Unauthorized(context);
|
|
return;
|
|
}
|
|
var jwt = option?.JwtTokenBuilder;
|
|
jwt.ThrowNullExceptionWhenNull();
|
|
var user = jwt.GetPlayload(token);
|
|
var userLogin = option?.UserLogin;
|
|
if (userLogin != null && !userLogin.CheckUserLogin(user)) {
|
|
Unauthorized(context);
|
|
return;
|
|
}
|
|
if (this.Roles != null && this.Roles.Count > 0 && !userLogin.UserInRoles(user, this.Roles)) {
|
|
Unauthorized(context);
|
|
return;
|
|
}
|
|
return;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 返回授权失败
|
|
/// </summary>
|
|
/// <param name="context">上下文</param>
|
|
private static void Unauthorized(AuthorizationFilterContext context) {
|
|
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
|
}
|
|
}
|
|
}
|