Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <JwtSeetings>(Configuration.GetSection("JwtSeetings"));

            var jwtSeetings = new JwtSeetings();

            //绑定jwtSeetings
            Configuration.Bind("JwtSeetings", jwtSeetings);
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtSeetings.Issuer,
                    ValidAudience    = jwtSeetings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSeetings.SecretKey))
                };
            })
            ;

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 使用 Microsoft.AspNetCore.Authentication.JwtBearer
        /// </summary>
        /// <param name="services"></param>
        private void JWTConfig(IServiceCollection services)
        {
            services.Configure <JwtSeetings>(Configuration.GetSection("JwtSeetings"));

            var jwtSeetings = new JwtSeetings();

            //绑定jwtSeetings
            Configuration.Bind("JwtSeetings", jwtSeetings);
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = true,
                    ClockSkew                = TimeSpan.FromMinutes(5),
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtSeetings.Issuer,
                    ValidAudience            = jwtSeetings.Audience,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSeetings.SecretKey))
                };
            });
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的
            services.Configure <JwtSeetings>(Configuration.GetSection("JwtSeetings"));

            //由于初始化的时候我们就需要用,所以使用Bind的方式读取配置
            //将配置绑定到JwtSettings实例中
            var jwtSettings = new JwtSeetings();

            Configuration.Bind("JwtSeetings", jwtSettings);

            //注入:JWT认证配置
            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o => {
//                 //主要是jwt配置  token参数设置
//                 o.TokenValidationParameters = new TokenValidationParameters{
//             //Token颁发机构
//                     ValidIssuer =jwtSettings.Issuer,
//             //颁发给谁
//                     ValidAudience =jwtSettings.Audience,
//                     //这里的key要进行加密,需要引用 Microsoft.IdentityModel.Tokens
//                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
//             //ValidateIssuerSigningKey=true,
//             ////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
//             //ValidateLifetime=true,
//             ////允许的服务器时间偏移量
//             //ClockSkew=TimeSpan.Zero

//                 };


                //自定义token取值
                o.SecurityTokenValidators.Clear();
                //修改token来源:默认是从请求头 context.Request.Headers["Authorization"] 中取
                //               现在可直接从 context.Request.Headers["token"] 取

                o.SecurityTokenValidators.Add(new CustomerTokenValidation());

                o.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context => {
                        var token     = context.Request.Headers["token"];
                        context.Token = token.FirstOrDefault();
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options => {
                options.AddPolicy("SuperAdminOnly", policy => policy.RequireClaim("SuperAdminOnly"));
            });



            services.AddControllers();
        }
Ejemplo n.º 4
0
 public AuthroizeController(IOptions <JwtSeetings> jwtSeetingsOptions, IUowProvider uowProvider)
 {
     if (jwtSeetingsOptions != null)
     {
         _jwtSeetings = jwtSeetingsOptions.Value;
     }
     _uowProvider = uowProvider;
 }
Ejemplo n.º 5
0
        public async Task <IActionResult> Login([FromServices] AccountService service, [FromServices] JwtSeetings jwtSeetings, [FromServices] IDateTimeService dateTimeService, [FromForm] LoginInputModel userLogin)
        {
            if (string.IsNullOrEmpty(userLogin.Account))
            {
                throw new BingoX.LogicException();
            }
            if (string.IsNullOrEmpty(userLogin.Password))
            {
                throw new BingoX.LogicException();
            }
            var user = service.Login(userLogin.Account, userLogin.Password);

            if (user == null)
            {
                throw new  UnauthorizedException("登錄失败,帐号或密碼错误");
            }
            if (user.State != CostControlWebApplication.Domain.CommonState.Enabled)
            {
                throw new UnauthorizedException("登錄失败,帐号已经注销");
            }
            var now   = dateTimeService.GetNow();
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSeetings.Secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()),
                new Claim("Account", user.Account),
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Role, user.RoleType.ToString()),
                new Claim("UserID", user.ID.ToString()),
            };


            var token = new JwtSecurityToken(
                jwtSeetings.Issuer,
                jwtSeetings.Audience,
                claims,
                now,
                now.AddDays(30),
                creds
                );
            var tokenstring = new JwtSecurityTokenHandler().WriteToken(token);

            Response.Headers.Add("Authorization", "Bearer " + tokenstring);
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

            if (Url.IsLocalUrl(userLogin.ReturnUrl))
            {
                return(Redirect(userLogin.ReturnUrl));
            }
            else
            {
                return(Redirect("/ProjectMaster"));
            }
        }
Ejemplo n.º 6
0
 public AuthroizeController(IOptions <JwtSeetings> jwtSeetingsOptions)
 {
     _jwtSeetings = jwtSeetingsOptions.Value;
 }
 public AuthorizeController(IOptions <JwtSeetings> JwtSeetings)
 {
     _jwtSeetings = JwtSeetings.Value;
 }