You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DSWMS/Vue.Net/VOL.Core/Extensions/AuthorizationResponse.cs

46 lines
1.8 KiB
C#

2 years ago
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using VOL.Core.Configuration;
using VOL.Core.Enums;
using VOL.Core.Services;
using VOL.Core.Utilities;
using ConvertHelper;
namespace VOL.Core.Extensions
{
public static class AuthorizationResponse
{
public static AuthorizationFilterContext FilterResult(
this AuthorizationFilterContext context,
HttpStatusCode statusCode,
string message = null)
{
context.Result = new ContentResult()
{
Content = new { message, status = false, code = (int)statusCode }.Serialize(),
ContentType = "application/json",
StatusCode = (int)statusCode
};
Logger.Info(LoggerType.ApiAuthorize, message);
return context;
}
public static AuthorizationFilterContext Unauthorized(this AuthorizationFilterContext context, string message = null)
{
return context.FilterResult(HttpStatusCode.Unauthorized, message);
}
//不通过JWT验证的直接将用户信息缓存起来
public static void AddIdentity(this AuthorizationFilterContext context, string userId=null)
{
string _userId = userId ?? JwtHelper.GetUserId(context.HttpContext.Request.Headers[AppSetting.TokenHeaderName]);
if (string.IsNullOrWhiteSpace(_userId)) return;
//将用户Id缓存到上下文(或者自定一个对象通过DI以AddScoped方式注入上下文来管理用户信息)
var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Jti, _userId.ToString()) };
context.HttpContext.User.AddIdentity(new ClaimsIdentity(claims));
}
}
}