Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            bool enable = Configuration.GetSection("Redis:Enabled").Get <bool>();

            if (enable)
            {
            }

            Console.WriteLine();
            #region swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title       = "MiMall API",
                    Version     = "v1",
                    Description = "框架说明文档",
                    Contact     = new Microsoft.OpenApi.Models.OpenApiContact()
                    {
                        Email = "*****@*****.**",
                        Name  = "MiMall",
                        Url   = new Uri("https://www.cnblogs.com/licm/")
                    }
                });

                //xml注释文档
                string basePath = Directory.GetCurrentDirectory();
                string fileName = Assembly.GetExecutingAssembly().GetName().Name;
                string xmlPath  = Path.Combine(basePath, fileName + ".xml");
                options.IncludeXmlComments(xmlPath, true);

                //model xml注释文档

                string modelPath    = basePath.Substring(0, basePath.LastIndexOf(fileName));
                string xmlModelPath = Path.Combine(basePath, "MiMall.Model.xml");
                options.IncludeXmlComments(xmlModelPath);

                //jwt 接口权限认证
                //添加安全定义
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description  = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token", //提示信息描述
                    Name         = "Authorization",                         //键名称
                    In           = ParameterLocation.Header,                //参数定义为头部请求参数
                    Type         = SecuritySchemeType.ApiKey,               //参数类型为apikey
                    BearerFormat = "JWT",                                   //持票人格式为jwt
                    Scheme       = "Bearer"                                 //验证体系为Bearer
                });
                //添加安全需求
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme()
                        {
                            Reference = new OpenApiReference()
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        }, new string[] { }
                    }
                });
            });
            #endregion

            #region Authentication && JWT
            JwtAuthModel model = Configuration.GetSection("JwtAuthModel").Get <JwtAuthModel>();
            services.AddAuthentication("Bearer")
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = model.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(model.SigningKey)),
                    ValidateAudience         = true,
                    ValidAudience            = model.Audience,
                    RequireExpirationTime    = true, //是否验证过期时间
                    ValidateLifetime         = true, //是否验证过期时间
                    ClockSkew = TimeSpan.Zero        ////这个是缓冲过期时间,也就是说,即使我们配置了过期时间,这里也要考虑进去,过期时间+缓冲,默认好像是7分钟,你可以直接设置为0
                };
                //自定义Token获取方式
                options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        //接收到请求消息后调用 (在Url中添加access_token=[token])
                        context.Token = context.Request.Cookies["access_token"];
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        //在token验证成功后调用
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("act", "expired");
                        }

                        //在token验证失败后调用
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        //未授权时调用
                        return(Task.CompletedTask);
                    },
                    OnForbidden = context =>
                    {
                        //被禁止时调用
                        return(Task.CompletedTask);
                    }
                };
            });    //.AddCookie();

            #endregion

            #region Authorization
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
                //或
                options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("System", "Admin").Build());
                options.AddPolicy("everyone", policy => policy.RequireRole("System", "Admin", "Client", "Partner").Build());
                //并
                options.AddPolicy("SystemAndAdmin", policy => policy.RequireRole("System")
                                  .RequireRole("Admin").Build());
            });
            #endregion

            #region Cors
            services.AddCors(options =>
            {
                //允许所有源,头文件、方法访问
                options.AddPolicy("any", policy =>
                {
                    policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                });
            });
            #endregion
        }
Esempio n. 2
0
        public TModel <dynamic> Login(string username, string password)
        {
            var user = _usersService.FirstOrDefault(u => u.UserName == username && u.Userpwd == password).Result;


            if (user == null)
            {
                return(new TModel <dynamic>()
                {
                    status = 20,
                    message = "用户名或密码错误",
                    Data = user
                });
            }
            else
            {
                string reoleNmae = _userRoleService.Find(user.RoleId).Result.RoleName;

                //声明参数
                Claim[] claims =
                {
                    new Claim(JwtRegisteredClaimNames.AuthTime, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss fff")),
                    new Claim(JwtRegisteredClaimNames.Sub,      user.UserId.ToString()),
                    new Claim(ClaimTypes.Role,                  reoleNmae)
                };
                //读取配置文件
                JwtAuthModel model = _configuration.GetSection("JwtAuthModel").Get <JwtAuthModel>();
                //创建token对象
                JwtSecurityToken token = new JwtSecurityToken(
                    issuer: model.Issuer,                                                    //发行人
                    audience: model.Audience,                                                //订阅人
                    claims: claims,                                                          //声明参数
                    expires: DateTime.Now.AddSeconds(model.AccessExpiration),                //过期时间
                    signingCredentials: new SigningCredentials(
                        new SymmetricSecurityKey(Encoding.ASCII.GetBytes(model.SigningKey)), //密钥
                        SecurityAlgorithms.HmacSha256)                                       //加密方式
                    );
                //生成token字符串
                string jwtString = new JwtSecurityTokenHandler().WriteToken(token);

                //获取刷新token
                string refTokens = GenerateRefreshToken();

                //写入cookie
                Response.Cookies.Append("access_token", jwtString, new CookieOptions()
                {
                    Expires = DateTime.Now.AddMinutes(30)
                });//访问token
                Response.Cookies.Append("refresh_token", refTokens, new CookieOptions()
                {
                    Expires = DateTime.Now.AddDays(7) //过期时间 7天
                });                                   //刷新token

                //获取token
                string cookie = Request.Cookies["access_token"];



                return(new TModel <dynamic>()
                {
                    status = 0,
                    message = "success",
                    Data = new
                    {
                        user
                        //,jwtString
                    }
                });
            }
        }