core JwtBearer

  • 1、自定义认证中间件 JwtTokenAuth
  • 2、Startup
  • Configure下:
  •  if (env.IsDevelopment())
                {
                    GlobalContext.SystemConfig.Debug = true;
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseCors("CorsPolicy");
                app.UseAuthentication();
                app.UseMiddleware<JwtTokenAuth>();
    
                string resource = Path.Combine(env.ContentRootPath, "Resource");
                FileHelper.CreateDirectory(resource);
    
                app.UseStaticFiles(new StaticFileOptions
                {
                    OnPrepareResponse = GlobalContext.SetCacheControl
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath = "/Resource",
                    FileProvider = new PhysicalFileProvider(resource),
                    OnPrepareResponse = GlobalContext.SetCacheControl
                });
    
                app.UseMiddleware(typeof(GlobalExceptionMiddleware));
    
                app.UseCors(builder =>
                {
                    builder.WithOrigins(GlobalContext.SystemConfig.AllowCorsSite.Split(',')).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
                });
                app.UseSwagger(c =>
                {
                    c.RouteTemplate = "api-doc/{documentName}/swagger.json";
                });
                app.UseSwaggerUI(c =>
                {
                    c.RoutePrefix = "api-doc";
                    c.SwaggerEndpoint("v1/swagger.json", "YiSha Api v1");
                });
                app.UseRouting();
    
                app.UseCors(cfg =>
                {
                    cfg.AllowAnyOrigin();
                    cfg.AllowAnyMethod(); 
                    cfg.AllowAnyHeader(); 
                });           
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute("default", "{controller=ApiHome}/{action=Index}/{id?}");
                });
                GlobalContext.ServiceProvider = app.ApplicationServices;
                if (!GlobalContext.SystemConfig.Debug)
                {
                    new JobCenter().Start(); // 定时任务
                }
    Configure

    ConfigureServices下:

  •  #region Cors 跨域
                services.AddCors(options => options.AddPolicy("CorsPolicy",
               builder =>
               {
                   builder.AllowAnyMethod()
                       .SetIsOriginAllowed(_ => true)
                       .AllowAnyHeader()
                       .AllowCredentials();
               }));   
                #endregion
    
                #region Swagger
                services.AddSwaggerGen(c =>
                {
    
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Supervise Api", Version = "v1" });                
                    //添加中文注释
                    var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                    var commentsFileName = "YiSha.Admin.WebApi.xml";
                    var xmlPath = Path.Combine(basePath, commentsFileName);
                    //默认的第二个参数是false,这个是controller的注释
                    c.IncludeXmlComments(xmlPath, true);
    
                    //添加Model类的注释
                    var modelfilename = "YiSha.Model.xml";
                    var modelxmlpath = Path.Combine(basePath, modelfilename);
                    c.IncludeXmlComments(modelxmlpath);
    
                    c.DocInclusionPredicate((docName, description) => true);
    
                    //services.AddAuthorization(options =>
                    //{
                    //    options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
                    //    options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                    //    options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System"));
                    //});
    
                    #region Token绑定到ConfigureServices
                    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Type = ReferenceType.SecurityScheme,
                                        Id = "Bearer"
                                    },
                                    Scheme = "oauth2",
                                    Name = "Bearer",
                                    In = ParameterLocation.Header,
                                },
                                new List<string>()
                            }
                        });
    
                    //添加设置Token的按钮
                    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "Bearer {token}",
                        Name = "Authorization",// jwt默认的参数名称
                        In = ParameterLocation.Header, // jwt默认存放Authorization信息的位置(请求头中)
                        Type = SecuritySchemeType.ApiKey,
                        Scheme = "Bearer"
                    });
                    #endregion
    
                });
                #endregion
    
    
    
                #region JWT
                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Audience:Secret"]));
                services.AddAuthentication("Bearer").AddJwtBearer(o => {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        //是否开启密钥认证和key值
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = signingKey,
    
                        //是否开启发行人认证和发行人
                        ValidateIssuer = true,
                        ValidIssuer = Configuration["Audience:Issuer"],
    
                        //是否开启订阅人认证和订阅人
                        ValidateAudience = true,
                        ValidAudience = Configuration["Audience:Audience"],
    
                        //认证时间的偏移量
                        //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                        ClockSkew = TimeSpan.FromSeconds(10800),                 
                        //是否开启时间认证
                        ValidateLifetime = true,
                        //是否该令牌必须带有过期时间
                        RequireExpirationTime = true,
                       
                    };
                });
                #endregion
    ConfigureServices

     

  • 3、appsettings
    "Audience": {
        "Secret": "11111111111111",
        "Issuer": "222222222",
        "Audience": "Nobody"
      },

     

  • 4、 Controller增加

  • [ApiController]
    [ApiController][AuthorizeFilter]
    [Authorize]

  • 5、AuthorizeFilter扩展
  •  string token = context.HttpContext.Request.Headers["Authorization"].ParseToString();
                if (!string.IsNullOrEmpty(token))
                {
                    token =token.Replace("Bearer ", "");
                }
                //token = (context.HttpContext.Request.Headers).HeaderAuthorization;
                OperatorInfo user = await Operator.Instance.Current(token);  
     if (user != null)
                {
                    // 根据传入的Token,设置CustomerId
                    if (context.ActionArguments != null && context.ActionArguments.Count > 0)
                    {
                        PropertyInfo property = context.ActionArguments.FirstOrDefault().Value.GetType().GetProperty("Token");
                        if (property != null)
                        {
                            property.SetValue(context.ActionArguments.FirstOrDefault().Value, token, null);
                        }
                        switch (context.HttpContext.Request.Method.ToUpper())
                        {
                            case "GET":
                                break;
    
                            case "POST":
                                property = context.ActionArguments.FirstOrDefault().Value.GetType().GetProperty("CustomerId");
                                if (property != null)
                                {
                                    property.SetValue(context.ActionArguments.FirstOrDefault().Value, user.UserId, null);
                                }
                                break;
                        }
                    }
                }
                else
                {
                    string actionName = ((ControllerActionDescriptor)context.ActionDescriptor).ActionName;
                    bool exists = ((IList)IgnoreToken).Contains(actionName);
                    if (!exists)
                    {
                        TData obj = new TData();
                        obj.Message = "抱歉,没有登录或登录已超时";
                        obj.Tag = 10;
                        context.Result = new JsonResult(obj);
                        return;
                    }                 
                }

     

posted @ 2022-03-10 15:53  丁焕轩  阅读(57)  评论(0编辑  收藏  举报