59 lines
2.6 KiB
C#
59 lines
2.6 KiB
C#
using Learn.Archives.Core.Common;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Net;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.Text;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Learn.Archives.Core.Model.Dto;
|
|
using Aliyun.OSS;
|
|
|
|
namespace Learn.Archives.API.Expand
|
|
{
|
|
public static class AuthorizeExpand
|
|
{
|
|
public static IServiceCollection AddPermissionAuthentication(this IServiceCollection services)
|
|
{
|
|
services.AddAuthentication()
|
|
.AddJwtBearer(Authentication.Admin, options =>
|
|
{
|
|
options.RequireHttpsMetadata = false;
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
SaveSigninToken = false,//保存token,后台验证token是否生效(重要)
|
|
RequireExpirationTime = true, // 设置请求需要携带accesstoken的过期时间
|
|
ValidateIssuer = false,//必须验证签发人
|
|
ValidateAudience = false,//验证受众
|
|
ValidateLifetime = true,//是否验证Token有效期
|
|
ValidateIssuerSigningKey = true,//是否验证签名,不验证 会被篡改数据,不安全
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppCommon.Config.AuthKey.Secret)),//解密的密钥
|
|
};
|
|
options.Events = new JwtBearerEvents
|
|
{
|
|
OnAuthenticationFailed = context =>
|
|
{
|
|
context.Response.Clear();
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = 403;
|
|
var data = new BaseReturn() { Code = 403, Message = context.Exception.Message + context.Exception?.StackTrace };
|
|
context.Response.WriteAsync(data.ToJson());
|
|
return Task.CompletedTask;
|
|
},
|
|
OnChallenge = context =>
|
|
{
|
|
context.HandleResponse();
|
|
context.Response.Clear();
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = 403;
|
|
var data = new BaseReturn() { Code = 403, Message = context.Error + context.AuthenticateFailure?.Message };
|
|
context.Response.WriteAsync(data.ToJson());
|
|
return Task.CompletedTask;
|
|
}
|
|
};
|
|
});
|
|
return services;
|
|
}
|
|
|
|
}
|
|
}
|