using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Core.Const;
using WIDESEAWCS_Core.Helper;
namespace WIDESEAWCS_Core.Authorization
{
///
/// 系统 授权服务 配置
///
public static class AuthorizationSetup
{
///
/// 系统 授权服务 配置
///
///
///
public static void AddAuthorizationSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
SaveSigninToken = true,//保存token,后台验证token是否生效(重要)
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = AppSecret.Audience,//Audience
ValidIssuer = AppSecret.Issuer,//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSecret.JWT))
};
options.Events = new JwtBearerEvents()
{
OnChallenge = context =>
{
context.HandleResponse();
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.StatusCode = 401;
context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize());
return Task.CompletedTask;
}
};
});
services.AddSingleton();
}
}
}