Exemple #1
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (!context.Request.Headers.ContainsKey("Authorization"))
                {
                    await _next(context);
                }
                else
                {
                    string authHeader = context.Request.Headers["Authorization"].FirstOrDefault();

                    if (!string.IsNullOrEmpty(authHeader))
                    {
                        var token = authHeader.Split(' ');
                        if (token.Length > 1)
                        {
                            if (token[0].ToLower() == "bearer")
                            {
                                var     jwtToken  = new JwtSecurityToken(token[1]);
                                var     paloadStr = JSONHelper.Seriallize(jwtToken.Payload);
                                JObject objs      = JsonConvert.DeserializeObject <JObject>(paloadStr);
                                //颁发机构
                                if (_jwt.Issuer != objs["iss"].ToString())
                                {
                                    throw new Exception("Token颁发机构异常");
                                }

                                //过期
                                if (DateTimeExtension.ConvertToCsharpTime(objs["exp"].ToSafeLong()) <= DateTime.Now)
                                {
                                    throw new Exception("授权已过期");
                                }

                                List <Claim> claims = new List <Claim>();
                                foreach (var property in objs)
                                {
                                    var claim = new Claim(property.Key.ToString(), property.Value.ToString());
                                    claims.Add(claim);
                                }

                                var ci = new ClaimsIdentity();
                                ci.AddClaims(claims);
                                context.User.AddIdentity(ci);

                                await _next(context);
                            }
                            else
                            {
                                throw new Exception("无法识别的Authorization类型");
                            }
                        }
                        else
                        {
                            throw new Exception("Authorization值不符合规范");
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                await context.Response.WriteAsync(exp.Message, Encoding.UTF8);
            }
        }
        public static void AddService(this IServiceCollection services, SysConfig systemConfig)
        {
            WebApiCompatShimMvcBuilderExtensions.AddWebApiConventions(services.AddMvc(opt =>
            {
                opt.UseCentralRoutePrefix(new RouteAttribute(systemConfig.Name));
            }))
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(x =>
            {
                //设置时间格式
                x.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //设置转换属性
                //x.SerializerSettings.ContractResolver = new ContractResolverOverload();
            });

            services.AddCors(opt =>
            {
                opt.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//指定处理cookie
                });
            });
            #region JWT认证
            //JWT配置注入
            services.Configure <JwtSettings>(opt =>
            {
                opt.Audience   = systemConfig.JwtSettings.Audience;
                opt.Expires    = systemConfig.JwtSettings.Expires;
                opt.Issuer     = systemConfig.JwtSettings.Issuer;
                opt.PrivateKey = systemConfig.JwtSettings.PrivateKey;
                opt.PublicKey  = systemConfig.JwtSettings.PublicKey;
                opt.Secretkey  = systemConfig.JwtSettings.Secretkey;
            });
            SysConfig systemConfig2 = systemConfig;
            services.AddMicroService(systemConfig2);

            //TODO 令牌过期后刷新,以及更改密码后令牌未过期的处理问题
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opts =>
            {
                opts.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        var header    = context.Request.Headers["Authorization"].FirstOrDefault();
                        var jwtEntity = JwtEntity.GetJwtEntity(header);
                        if (jwtEntity != null)
                        {
                            if (DateTime.Now > DateTimeExtension.ConvertToCsharpTime(jwtEntity.Exp))
                            {
                                context.Fail("token已过期");
                            }
                        }
                        return(Task.CompletedTask);
                    }
                };

                opts.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(systemConfig.JwtSettings.Secretkey)),
                    ValidateIssuer           = true,
                    ValidIssuer      = systemConfig.JwtSettings.Issuer,
                    ValidateAudience = true,
                    ValidAudience    = systemConfig.JwtSettings.Audience,
                };
            });
            #endregion
        }