¶Ô±ÈÐÂÎļþ |
| | |
| | | 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 WIDESEA_Core.Const; |
| | | using WIDESEA_Core.Helper; |
| | | |
| | | namespace WIDESEA_Core.Authorization |
| | | { |
| | | /// <summary> |
| | | /// ç³»ç» æææå¡ é
ç½® |
| | | /// </summary> |
| | | public static class AuthorizationSetup |
| | | { |
| | | /// <summary> |
| | | /// ç³»ç» æææå¡ é
ç½® |
| | | /// </summary> |
| | | /// <param name="services"></param> |
| | | /// <exception cref="ArgumentNullException"></exception> |
| | | 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<IHttpContextAccessor, HttpContextAccessor>(); |
| | | } |
| | | } |
| | | } |