Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            var jwtSection = Configuration.GetSection(JwtOption.Name);

            services.Configure <JwtOption>(jwtSection);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                var jwtOption = new JwtOption();
                jwtSection.Bind(jwtOption);

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOption.SecretKey)),
                    ValidateLifetime = jwtOption.ValidateLifetime,
                    ValidIssuer      = jwtOption.ValidIssuer,
                    ValidAudience    = jwtOption.ValidAudience,
                    ValidateAudience = jwtOption.ValidateAudience,
                    ValidateIssuer   = jwtOption.ValidateIssuer,
                };
            });
        }
Пример #2
0
        /// <summary>
        /// 生成JwtToken
        /// </summary>
        public static string CreateToken(Claim[] claims, JwtOption jwtOption)
        {
            string secret = jwtOption.Secret;

            if (secret == null)
            {
                throw new Exception("创建JwtToken时Secret为空");
            }
            SecurityKey        key         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));
            SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
            DateTime           now         = DateTime.Now;
            double             days        = Math.Abs(jwtOption.ExpireDays);
            DateTime           expires     = now.AddDays(days);

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Audience           = jwtOption.Audience,
                Issuer             = jwtOption.Issuer,
                SigningCredentials = credentials,
                NotBefore          = now,
                IssuedAt           = now,
                Expires            = expires
            };
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken           token        = tokenHandler.CreateToken(descriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #3
0
        public void InstallServices(IServiceCollection services)
        {
            var jwtOptions = new JwtOption
            {
                Issuer                 = "patientTracking.net",
                Audience               = "patientTracking.net",
                SecurityKey            = "F2peYX7865Yk8wztCxg8jzZGF5yEx4vu4TK4mN8DLtsVpnGa3V5jabYjFhGf",
                AccessTokenExpiration  = 15,
                RefreshTokenExpiration = 60 * 24 * 10
            };

            services.AddSingleton(jwtOptions);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidIssuer              = jwtOptions.Issuer,
                    ValidAudience            = jwtOptions.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey)),
                    ClockSkew = TimeSpan.Zero
                };
            });
        }
Пример #4
0
        public UserController(IOptions <JwtOption> options)
        {
            jwtOption = options.Value;
            jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOption.SecretKey));

            signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
        }
Пример #5
0
 public UserController(IUserRepository userRepository,
                       ITimeService timeService,
                       IOptions <JwtOption> jwtOptions)
 {
     _userRepository = userRepository;
     _timeService    = timeService;
     _jwtOption      = jwtOptions.Value;
 }
        private void ParseToken(HttpContext context, string token)
        {
            try
            {
                JwtOption jwtOption = _db.JwtOption.FirstOrDefault();

                if (jwtOption == null)
                {
                    throw new Exception("JwtOption was null");
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(jwtOption.Key);

                SecurityToken SignatureValidator(string encodedToken, TokenValidationParameters parameters)
                {
                    var jwt = new JwtSecurityToken(encodedToken);

                    var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(jwtOption.Key));

                    var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(hmac.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

                    var signKey = signingCredentials.Key as SymmetricSecurityKey;

                    var encodedData       = jwt.EncodedHeader + "." + jwt.EncodedPayload;
                    var compiledSignature = Encode(encodedData, signKey.Key);

                    if (compiledSignature != jwt.RawSignature)
                    {
                        throw new Exception("Token signature validation failed.");
                    }

                    return(jwt);
                }

                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireSignedTokens      = false, //погугли
                    ClockSkew          = TimeSpan.Zero,
                    SignatureValidator = SignatureValidator,
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                context.User = new GenericPrincipal(new AuthorizedUserModel
                {
                    RoleId = int.Parse(jwtToken.Claims.First(x => x.Type == ClaimsIdentity.DefaultNameClaimType).Value),
                    UserId = int.Parse(jwtToken.Claims.First(x => x.Type == ClaimsIdentity.DefaultRoleClaimType).Value),
                }, new [] { "" });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 public IdentityController(
     ILogger <IdentityController> logger,
     IOptions <JwtOption> option,
     IIdentityContract identityContract)
 {
     _logger           = logger;
     _option           = option.Value;
     _identityContract = identityContract;
 }
Пример #8
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="iAPPService"></param>
 /// <param name="_userService"></param>
 /// <param name="jwtModel"></param>
 public TokenController(IAPPService iAPPService, IUserService _userService, JwtOption jwtModel)
 {
     if (iAPPService == null)
     {
         throw new ArgumentNullException(nameof(iAPPService));
     }
     _iAPPService = iAPPService;
     userService  = _userService;
     _jwtModel    = jwtModel;
 }
Пример #9
0
 public TokenService(
     ILogger <TokenService> logger,
     IOptions <Configs> configs
     )
 {
     _configs    = configs.Value;
     _jwtOptions = _configs.JwtOption;
     _logger     = logger;
     _dc         = CreateDC();
 }
Пример #10
0
        public JwtFactory(IJwtTokenHandler jwtTokenHandler, IOptions <JwtIssuerOptions> jwtOptions,
                          IJwtTokenValidator jwtTokenValidator, IOptions <JwtOption> jwtOption)
        {
            _jwtTokenHandler   = jwtTokenHandler;
            _jwtOptions        = jwtOptions.Value;
            _jwtTokenValidator = jwtTokenValidator;
            _jwtOption         = jwtOption.Value;

            ThrowIfInvalidOptions(_jwtOptions);
        }
Пример #11
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         logger        = null;
         userMgr       = null;
         roleMgr       = null;
         jwt           = null;
         navRepo       = null;
         cache         = null;
         userTokenRepo = null;
         usersCtrl     = null;
         privilegeRepo = null;
         commonOption  = null;
     }
     base.Dispose(disposing);
 }
Пример #12
0
        public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration, string section)
        {
            var jwtOption  = new JwtOption();
            var jwtSection = configuration.GetSection(section);

            jwtSection.Bind(jwtOption);

            return(services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                   .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOption.SecretKey)),
                    ValidIssuer = jwtOption.Issuer,
                    ValidateAudience = false,
                    ValidateLifetime = jwtOption.ValidateLifetime
                };
            }));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //string datebaseconnectionstring = "Host=185.87.48.116;Database=postgres;Username=postgres;Password=123123AAA";
            string datebaseconnectionstring = Environment.GetEnvironmentVariable("datebaseconnectionstring");

            services.AddTransient(x =>
            {
                return(new MainContext(datebaseconnectionstring));
            });


            MainContext context = new MainContext(datebaseconnectionstring);

            JwtOption jwtOption = context.JwtOption.FirstOrDefault();

            services.AddSingleton(new AuthOptions(jwtOption.Key, jwtOption.Issuer, jwtOption.Audience));

            services.AddTransient <IAuthService, AuthService>();


            services.AddSwaggerGen();
        }
Пример #14
0
 public AccountController(
     ILogger <AccountController> logger,
     UserManager <AppUser> userMgr,
     RoleManager <AppRole> roleMgr,
     IOptionsSnapshot <JwtOption> jwt,
     IAppNavItemRepository navRepo,
     IDistributedCache cache,
     IAppUserTokenRepository userTokenRepo,
     UsersController usersCtrl,
     IAppPrivilegeRepository privilegeRepo,
     CommonOption commonOption
     )
 {
     this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     this.userMgr       = userMgr ?? throw new ArgumentNullException(nameof(userMgr));
     this.roleMgr       = roleMgr ?? throw new ArgumentNullException(nameof(roleMgr));
     this.jwt           = jwt.Value ?? throw new ArgumentNullException(nameof(jwt));
     this.navRepo       = navRepo ?? throw new ArgumentNullException(nameof(navRepo));
     this.cache         = cache ?? throw new ArgumentNullException(nameof(cache));
     this.userTokenRepo = userTokenRepo ?? throw new ArgumentNullException(nameof(userTokenRepo));
     this.usersCtrl     = usersCtrl ?? throw new ArgumentNullException(nameof(usersCtrl));
     this.privilegeRepo = privilegeRepo ?? throw new ArgumentNullException(nameof(privilegeRepo));
     this.commonOption  = commonOption ?? throw new ArgumentNullException(nameof(commonOption));
 }
Пример #15
0
        /// <summary>
        /// 添加验证
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            //   .AddCloudFoundryJwtBearer(configuration);
            //services.Configure<JwtOption>(configuration.GetSection("JwtOptions"));
            //由于初始化的时候我们就需要用,所以使用Bind的方式读取配置
            //将配置绑定到JwtSettings实例中
            var jwtSettings = new JwtOption();

            configuration.Bind("JwtOptions", jwtSettings);
            services.AddAuthentication(options =>
            {
                //认证middleware配置
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                var key = jwtSettings.SecretKey;
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer   = false,
                    //Token颁发机构
                    ValidIssuer = jwtSettings.Issuer,
                    //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
                    //ValidateIssuerSigningKey=true,
                    ////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true,
                    ////允许的服务器时间偏移量
                    ClockSkew = TimeSpan.FromSeconds(1)
                };
            });
            return(services);
        }
Пример #16
0
 public AccountController(IOptionsMonitor <JwtOption> option, SigningCredentials signingCredentials, UserService userService)
 {
     _signingCredentials = signingCredentials;
     _userService        = userService;
     _jwtOption          = option.CurrentValue;
 }
Пример #17
0
 public JwtProvider(IOptions <JwtOption> options)
 {
     _options = options.Value;
 }
Пример #18
0
        public async Task <IActionResult> GetCheckUser(string username, string password, string vcode, string vkey, string appId, string systemCode)
        {
            CommonResult      result            = new CommonResult();
            RemoteIpParser    remoteIpParser    = new RemoteIpParser();
            string            strIp             = remoteIpParser.GetClientIp(HttpContext).MapToIPv4().ToString();
            YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
            var    vCode = yuebonCacheHelper.Get("ValidateCode" + vkey);
            string code  = vCode != null?vCode.ToString() : "11";

            if (vcode.ToUpper() != code)
            {
                result.ErrMsg = "验证码错误";
                return(ToJsonContent(result));
            }
            Log  logEntity = new Log();
            bool blIp      = _filterIPService.ValidateIP(strIp);

            if (blIp)
            {
                result.ErrMsg = strIp + "该IP已被管理员禁止登录!";
            }
            else
            {
                if (string.IsNullOrEmpty(username))
                {
                    result.ErrMsg = "用户名不能为空!";
                }
                else if (string.IsNullOrEmpty(password))
                {
                    result.ErrMsg = "密码不能为空!";
                }
                if (string.IsNullOrEmpty(systemCode))
                {
                    result.ErrMsg = ErrCode.err40006;
                }
                else
                {
                    string strHost = Request.Host.ToString();
                    APP    app     = _appService.GetAPP(appId);
                    if (app == null)
                    {
                        result.ErrCode = "40001";
                        result.ErrMsg  = ErrCode.err40001;
                    }
                    else
                    {
                        if (!app.RequestUrl.Contains(strHost, StringComparison.Ordinal) && !strHost.Contains("localhost", StringComparison.Ordinal))
                        {
                            result.ErrCode = "40002";
                            result.ErrMsg  = ErrCode.err40002 + ",你当前请求主机:" + strHost;
                        }
                        else
                        {
                            SystemType systemType = _systemTypeService.GetByCode(systemCode);
                            if (systemType == null)
                            {
                                result.ErrMsg = ErrCode.err40006;
                            }
                            else
                            {
                                Tuple <User, string> userLogin = await this._userService.Validate(username, password);

                                if (userLogin != null)
                                {
                                    string ipAddressName = IpAddressUtil.GetCityByIp(strIp);
                                    if (userLogin.Item1 != null)
                                    {
                                        result.Success = true;
                                        User              user           = userLogin.Item1;
                                        JwtOption         jwtModel       = App.GetService <JwtOption>();
                                        TokenProvider     tokenProvider  = new TokenProvider(jwtModel);
                                        TokenResult       tokenResult    = tokenProvider.LoginToken(user, appId);
                                        YuebonCurrentUser currentSession = new YuebonCurrentUser
                                        {
                                            UserId         = user.Id,
                                            Name           = user.RealName,
                                            AccessToken    = tokenResult.AccessToken,
                                            AppKey         = appId,
                                            CreateTime     = DateTime.Now,
                                            Role           = _roleService.GetRoleEnCode(user.RoleId),
                                            ActiveSystemId = systemType.Id,
                                            CurrentLoginIP = strIp,
                                            IPAddressName  = ipAddressName
                                        };
                                        TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now;
                                        yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true);

                                        List <AllowCacheApp> list = yuebonCacheHelper.Get("AllowAppId").ToJson().ToList <AllowCacheApp>();
                                        if (list.Count == 0)
                                        {
                                            IEnumerable <APP> appList = _appService.GetAllByIsNotDeleteAndEnabledMark();
                                            yuebonCacheHelper.Add("AllowAppId", appList);
                                        }
                                        CurrentUser    = currentSession;
                                        result.ResData = currentSession;
                                        result.ErrCode = ErrCode.successCode;
                                        result.Success = true;

                                        logEntity.Account       = user.Account;
                                        logEntity.NickName      = user.NickName;
                                        logEntity.Date          = logEntity.CreatorTime = DateTime.Now;
                                        logEntity.IPAddress     = CurrentUser.CurrentLoginIP;
                                        logEntity.IPAddressName = CurrentUser.IPAddressName;
                                        logEntity.Result        = true;
                                        logEntity.ModuleName    = "登录";
                                        logEntity.Description   = "登录成功";
                                        logEntity.Type          = "Login";
                                        _logService.Insert(logEntity);
                                    }
                                    else
                                    {
                                        result.ErrCode          = ErrCode.failCode;
                                        result.ErrMsg           = userLogin.Item2;
                                        logEntity.Account       = username;
                                        logEntity.Date          = logEntity.CreatorTime = DateTime.Now;
                                        logEntity.IPAddress     = strIp;
                                        logEntity.IPAddressName = ipAddressName;
                                        logEntity.Result        = false;
                                        logEntity.ModuleName    = "登录";
                                        logEntity.Type          = "Login";
                                        logEntity.Description   = "登录失败," + userLogin.Item2;
                                        _logService.Insert(logEntity);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            yuebonCacheHelper.Remove("LoginValidateCode");
            return(ToJsonContent(result, true));
        }
Пример #19
0
        public IActionResult SysConnect(string openmf, string appId, string systemCode)
        {
            CommonResult   result         = new CommonResult();
            RemoteIpParser remoteIpParser = new RemoteIpParser();
            string         strIp          = remoteIpParser.GetClientIp(HttpContext).MapToIPv4().ToString();

            if (string.IsNullOrEmpty(openmf))
            {
                result.ErrMsg = "切换参数错误!";
            }

            bool blIp = _filterIPService.ValidateIP(strIp);

            if (blIp)
            {
                result.ErrMsg = strIp + "该IP已被管理员禁止登录!";
            }
            else
            {
                string ipAddressName = IpAddressUtil.GetCityByIp(strIp);
                if (string.IsNullOrEmpty(systemCode))
                {
                    result.ErrMsg = ErrCode.err40006;
                }
                else
                {
                    string strHost = Request.Host.ToString();
                    APP    app     = _appService.GetAPP(appId);
                    if (app == null)
                    {
                        result.ErrCode = "40001";
                        result.ErrMsg  = ErrCode.err40001;
                    }
                    else
                    {
                        if (!app.RequestUrl.Contains(strHost, StringComparison.Ordinal) && !strHost.Contains("localhost", StringComparison.Ordinal))
                        {
                            result.ErrCode = "40002";
                            result.ErrMsg  = ErrCode.err40002 + ",你当前请求主机:" + strHost;
                        }
                        else
                        {
                            SystemType systemType = _systemTypeService.GetByCode(systemCode);
                            if (systemType == null)
                            {
                                result.ErrMsg = ErrCode.err40006;
                            }
                            else
                            {
                                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                                object            cacheOpenmf       = yuebonCacheHelper.Get("openmf" + openmf);
                                yuebonCacheHelper.Remove("openmf" + openmf);
                                if (cacheOpenmf == null)
                                {
                                    result.ErrCode = "40007";
                                    result.ErrMsg  = ErrCode.err40007;
                                }
                                else
                                {
                                    User user = _userService.Get(cacheOpenmf.ToString());
                                    if (user != null)
                                    {
                                        result.Success = true;
                                        JwtOption         jwtModel       = App.GetService <JwtOption>();
                                        TokenProvider     tokenProvider  = new TokenProvider(jwtModel);
                                        TokenResult       tokenResult    = tokenProvider.LoginToken(user, appId);
                                        YuebonCurrentUser currentSession = new YuebonCurrentUser
                                        {
                                            UserId          = user.Id,
                                            Name            = user.RealName,
                                            AccessToken     = tokenResult.AccessToken,
                                            AppKey          = appId,
                                            CreateTime      = DateTime.Now,
                                            Role            = _roleService.GetRoleEnCode(user.RoleId),
                                            ActiveSystemId  = systemType.Id,
                                            CurrentLoginIP  = strIp,
                                            IPAddressName   = ipAddressName,
                                            ActiveSystemUrl = systemType.Url
                                        };
                                        TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now;
                                        yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true);
                                        CurrentUser    = currentSession;
                                        result.ResData = currentSession;
                                        result.ErrCode = ErrCode.successCode;
                                        result.Success = true;
                                    }
                                    else
                                    {
                                        result.ErrCode = ErrCode.failCode;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(ToJsonContent(result));
        }
Пример #20
0
        /// <summary>
        /// IoC初始化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private void InitIoC(IServiceCollection services)
        {
            #region 缓存
            CacheProvider cacheProvider = new CacheProvider
            {
                IsUseRedis       = Configuration.GetSection("CacheProvider:UseRedis").Value.ToBool(false),
                ConnectionString = Configuration.GetSection("CacheProvider:Redis_ConnectionString").Value,
                InstanceName     = Configuration.GetSection("CacheProvider:Redis_InstanceName").Value
            };

            var options = new JsonSerializerOptions();
            options.Encoder              = JavaScriptEncoder.Create(UnicodeRanges.All);
            options.WriteIndented        = true;
            options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            options.AllowTrailingCommas  = true;
            //设置时间格式
            options.Converters.Add(new DateTimeJsonConverter());
            options.Converters.Add(new DateTimeNullableConverter());
            //设置bool获取格式
            options.Converters.Add(new BooleanJsonConverter());
            //设置数字
            options.Converters.Add(new IntJsonConverter());
            options.PropertyNamingPolicy        = new UpperFirstCaseNamingPolicy();
            options.PropertyNameCaseInsensitive = true;                     //忽略大小写
            //判断是否使用Redis,如果不使用 Redis就默认使用 MemoryCache
            if (cacheProvider.IsUseRedis)
            {
                //Use Redis
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = cacheProvider.ConnectionString;
                    options.InstanceName  = cacheProvider.InstanceName;
                });
                services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
                {
                    Configuration = cacheProvider.ConnectionString,
                    InstanceName  = cacheProvider.InstanceName
                }, options, 0));
                services.Configure <DistributedCacheEntryOptions>(option => option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));//设置Redis缓存有效时间为5分钟。
            }
            else
            {
                //Use MemoryCache
                services.AddSingleton <IMemoryCache>(factory =>
                {
                    var cache = new MemoryCache(new MemoryCacheOptions());
                    return(cache);
                });
                services.AddSingleton <ICacheService, MemoryCacheService>();
                services.Configure <MemoryCacheEntryOptions>(
                    options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)); //设置MemoryCache缓存有效时间为5分钟
            }
            services.AddTransient <MemoryCacheService>();
            services.AddMemoryCache();            // 启用MemoryCache

            services.AddSingleton(cacheProvider); //注册缓存配置
            #endregion

            #region 身份认证授权

            var jwtConfig = Configuration.GetSection("Jwt");
            var jwtOption = new JwtOption
            {
                Issuer         = jwtConfig["Issuer"],
                Expiration     = Convert.ToInt16(jwtConfig["Expiration"]),
                Secret         = jwtConfig["Secret"],
                Audience       = jwtConfig["Audience"],
                refreshJwtTime = Convert.ToInt16(jwtConfig["refreshJwtTime"])
            };
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtOption.Secret)),//秘钥
                    ValidateIssuer           = true,
                    ValidIssuer      = jwtOption.Issuer,
                    ValidateAudience = true,
                    ValidAudience    = jwtOption.Audience,
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(5)
                };
            });
            services.AddSingleton(jwtOption);//注册配置
            #endregion

            services.AddAutoScanInjection();                          //自动化注入仓储和服务
            services.AddTransient <IDbContextCore, MySqlDbContext>(); //注入EF上下文

            #region automapper
            List <Assembly> myAssembly = RuntimeHelper.GetAllYuebonAssemblies().ToList();
            services.AddAutoMapper(myAssembly);
            services.AddTransient <IMapper, Mapper>();
            #endregion

            #region 定时任务
            services.AddTransient <HttpResultfulJob>();
            services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>();
            //设置定时启动的任务
            services.AddHostedService <QuartzService>();
            #endregion
            App.Services = services;
        }
Пример #21
0
        public IActionResult OnLogin(string code)
        {
            CommonResult result = new CommonResult();

            try
            {
                var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code);
                if (jsonResult.errcode == ReturnCode.请求成功)
                {
                    //使用SessionContainer管理登录信息(推荐)
                    var unionId    = jsonResult.unionid;
                    var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId);

                    //注意:生产环境下SessionKey属于敏感信息,不能进行传输!
                    //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey });

                    YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                    //User user = userApp.GetUserByUnionId(unionId);
                    User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid);
                    if (user == null)
                    {
                        UserInputDto userInput = new UserInputDto();
                        userInput.OpenId     = jsonResult.openid;
                        user.UnionId         = jsonResult.unionid;
                        userInput.OpenIdType = "yuebon.openid.wxapplet";
                        userInput.NickName   = "游客";
                        userInput.UnionId    = jsonResult.unionid;
                        result.Success       = userService.CreateUserByWxOpenId(userInput);
                    }
                    //针对老用户更新UnionId
                    if (user != null && string.IsNullOrEmpty(user.UnionId))
                    {
                        user.UnionId   = jsonResult.unionid;
                        result.Success = userService.Update(user, user.Id);
                    }
                    string userId = string.Empty;
                    if (result.ResData != null)
                    {
                        userId = result.ResData.ToString();
                    }
                    if (user == null)
                    {
                        user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid);
                    }

                    var currentSession = (YuebonCurrentUser)(yuebonCacheHelper.Get("login_user_" + userId));
                    if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken))
                    {
                        JwtOption     jwtModel      = App.GetService <JwtOption>();
                        TokenProvider tokenProvider = new TokenProvider(jwtModel);
                        TokenResult   tokenResult   = tokenProvider.LoginToken(user, "wxapplet");
                        currentSession = new YuebonCurrentUser
                        {
                            UserId         = user.Id,
                            Account        = user.Account,
                            Name           = user.RealName,
                            NickName       = user.NickName,
                            AccessToken    = tokenResult.AccessToken,
                            AppKey         = "wxapplet",
                            CreateTime     = DateTime.Now,
                            HeadIcon       = user.HeadIcon,
                            Gender         = user.Gender,
                            ReferralUserId = user.ReferralUserId,
                            MemberGradeId  = user.MemberGradeId,
                            Role           = roleService.GetRoleEnCode(user.RoleId),
                            MobilePhone    = user.MobilePhone,
                            WxSessionId    = sessionBag.Key
                        };
                        TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now;
                        yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true);
                    }
                    CurrentUser    = currentSession;
                    result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account);
                    result.ErrCode = ErrCode.successCode;
                    result.Success = true;
                }
                else
                {
                    result.ErrCode = ErrCode.failCode;
                    result.ErrMsg  = jsonResult.errmsg;
                }
            }
            catch (Exception ex)
            {
                result.ErrMsg = ex.Message;
            }

            return(ToJsonContent(result));
        }
Пример #22
0
        public IActionResult QuikLogin(WxUserInfo info)
        {
            CommonResult result = new CommonResult();

            try
            {
                if (info != null)
                {
                    DecodedUserInfo decodedUserInfo = EncryptHelper.DecodeUserInfoBySessionId(info.SessionId, info.EncryptedData, info.Iv);

                    UserInputDto userInput = new UserInputDto();
                    userInput.NickName       = decodedUserInfo.nickName;
                    userInput.HeadIcon       = decodedUserInfo.avatarUrl;
                    userInput.Gender         = decodedUserInfo.gender;
                    userInput.Country        = decodedUserInfo.country;
                    userInput.Province       = decodedUserInfo.province;
                    userInput.City           = decodedUserInfo.city;
                    userInput.language       = info.language;
                    userInput.OpenId         = decodedUserInfo.openId;
                    userInput.OpenIdType     = "yuebon.openid.wxapplet";
                    userInput.ReferralUserId = info.ReferralUserId;
                    userInput.UnionId        = decodedUserInfo.unionId;
                    User user = userService.GetUserByOpenId(userInput.OpenIdType, decodedUserInfo.openId);
                    if (user == null)
                    {
                        result.Success = userService.CreateUserByWxOpenId(userInput);
                    }
                    else
                    {
                        result.Success = userService.UpdateUserByOpenId(userInput);
                    }
                    user = userService.GetUserByOpenId(info.openIdType, info.openId);
                    if (user != null)
                    {
                        JwtOption     jwtModel       = App.GetService <JwtOption>();
                        TokenProvider tokenProvider  = new TokenProvider(jwtModel);
                        TokenResult   tokenResult    = tokenProvider.LoginToken(user, "wxapplet");
                        var           currentSession = new YuebonCurrentUser
                        {
                            UserId         = user.Id,
                            Account        = user.Account,
                            Name           = user.RealName,
                            NickName       = user.NickName,
                            AccessToken    = tokenResult.AccessToken,
                            AppKey         = "wxapplet",
                            CreateTime     = DateTime.Now,
                            HeadIcon       = user.HeadIcon,
                            Gender         = user.Gender,
                            ReferralUserId = user.ReferralUserId,
                            MemberGradeId  = user.MemberGradeId,
                            Role           = roleService.GetRoleEnCode(user.RoleId)
                        };

                        CurrentUser = currentSession;
                        YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                        TimeSpan          expiresSliding    = DateTime.Now.AddMinutes(120) - DateTime.Now;
                        yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true);
                        result.ErrCode = ErrCode.successCode;
                        result.ResData = currentSession;
                        result.Success = true;
                    }
                    else
                    {
                        result.ErrCode = ErrCode.failCode;
                    }
                }
            }catch (Exception ex)
            {
                Log4NetHelper.Error("微信快速(一键)登录异常", ex);
                result.ErrMsg  = "微信快速(一键)登录:" + ex.Message;
                result.ErrCode = ErrCode.failCode;
            }
            return(ToJsonContent(result));
        }
Пример #23
0
        public static IServiceCollection AddAuthService(this IServiceCollection services, JwtOption jwtOption)
        {
            services.AddSingleton <JwtSecurityTokenHandler>();
            services.AddSingleton <IJwtService, JwtService>();

            #region 注册【认证】服务
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = "RayPI",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOption.SecurityKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens   = true,
                    RequireExpirationTime = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // ClockSkew = TimeSpan.FromSeconds(300),// 允许的服务器时间偏移量
                    ValidateLifetime = true    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        //Token expired
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            #endregion

            #region 注册【授权】服务
            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyEnum.RequireRoleOfClient.ToString(), policy => policy.AddRequirements(new PolicyRequirement("Client")));
                options.AddPolicy(PolicyEnum.RequireRoleOfAdmin.ToString(), policy => policy.AddRequirements(new PolicyRequirement("Admin")));
                options.AddPolicy(PolicyEnum.RequireRoleOfAdminOrClient.ToString(), policy => policy.AddRequirements(new PolicyRequirement("Admin,Client")));
            });
            #endregion

            services.AddSingleton <IAuthorizationHandler, PolicyHandler>();

            //注册IOperateInfo
            services.AddScoped <IOperateInfo, OperateInfo>();

            return(services);
        }
Пример #24
0
        public IActionResult LoginByOpenId(string openId)
        {
            CommonResult result = new CommonResult();

            try
            {
                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", openId);
                if (user == null)
                {
                    UserInputDto userInput = new UserInputDto();
                    userInput.OpenId     = openId;
                    userInput.OpenIdType = "yuebon.openid.wxapplet";
                    userInput.NickName   = "游客";
                    result.Success       = userService.CreateUserByWxOpenId(userInput);
                }
                string userId = string.Empty;
                if (result.ResData != null)
                {
                    userId = result.ResData.ToString();
                }
                if (user == null)
                {
                    user = userService.GetUserByOpenId("yuebon.openid.wxapplet", openId);
                }
                var currentSession = (YuebonCurrentUser)yuebonCacheHelper.Get("login_user_" + user.Id);
                if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken))
                {
                    JwtOption     jwtModel      = App.GetService <JwtOption>();
                    TokenProvider tokenProvider = new TokenProvider(jwtModel);
                    TokenResult   tokenResult   = tokenProvider.LoginToken(user, "wxapplet");
                    currentSession = new YuebonCurrentUser
                    {
                        UserId         = user.Id,
                        Account        = user.Account,
                        Name           = user.RealName,
                        NickName       = user.NickName,
                        AccessToken    = tokenResult.AccessToken,
                        AppKey         = "wxapplet",
                        CreateTime     = DateTime.Now,
                        HeadIcon       = user.HeadIcon,
                        Gender         = user.Gender,
                        ReferralUserId = user.ReferralUserId,
                        MemberGradeId  = user.MemberGradeId,
                        Role           = roleService.GetRoleEnCode(user.RoleId),
                        MobilePhone    = user.MobilePhone
                    };
                    TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now;
                    yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true);
                }
                CurrentUser    = currentSession;
                result.ErrCode = ErrCode.successCode;
                result.Success = true;
                result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account);
            }
            catch (Exception ex)
            {
                Log4NetHelper.Error("微信登录异常 LoginByOpenId", ex);
                result.ErrMsg  = "微信登录异常:" + ex.Message;
                result.ErrCode = ErrCode.successCode;
            }

            return(ToJsonContent(result));
        }
Пример #25
0
 /// <summary>
 /// 构造函数,初花jwtmodel
 /// </summary>
 /// <param name="jwtModel"></param>
 public TokenProvider(JwtOption jwtModel)
 {
     _jwtModel = jwtModel;
 }
Пример #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            int a = 1;

            services.AddControllers();
            //string datebaseconnectionstring = "Host=185.87.48.116;Database=postgres;Username=postgres;Password=123123";
            string datebaseconnectionstring = Environment.GetEnvironmentVariable("datebaseconnectionstring");

            services.AddTransient(x =>
            {
                return(new MainContext(datebaseconnectionstring));
            });

            MainContext context = new MainContext(datebaseconnectionstring);

            JwtOption jwtOption = context.JwtOption.FirstOrDefault();

            AuthOptions authOptions = new AuthOptions(jwtOption.Key, jwtOption.Issuer, jwtOption.Audience);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = authOptions.ISSUER,

                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = authOptions.AUDIENCE,
                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // установка ключа безопасности
                    IssuerSigningKey = authOptions.GetSymmetricSecurityKey(),
                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddTransient <IContentService, ContentService>();

            services.AddTransient <ICategoryService, CategoryService>();

            services.AddTransient <IGroupService, GroupService>();

            services.AddTransient <ISourceService, SourceService>();

            services.AddTransient <IUserCredentialService, UserCredentialService>();

            services.AddAuthorizationCore(options =>
            {
                options.AddPolicy("AdminRole", policy =>
                                  policy.Requirements.Add(new RoleEntryRequirement(1)));
            });

            services.AddSingleton <IAuthorizationHandler, RoleEntryHandler>();

            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mapperConfig.CreateMapper();

            services.AddSingleton(mapper);


            services.AddSwaggerGen();
        }
Пример #27
0
 public UserService(LolaFloraDbContext dbContext, IOptions <JwtOption> jwtOptionSetting) : base(dbContext)
 {
     _jwtOption = jwtOptionSetting.Value;
 }
Пример #28
0
        /// <summary>
        /// IoC初始化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddMemoryCache();
            CacheProvider cacheProvider = new CacheProvider
            {
                IsUseRedis       = Configuration.GetSection("CacheProvider:UseRedis").Value.ToBool(false),
                ConnectionString = Configuration.GetSection("CacheProvider:Redis_ConnectionString").Value,
                InstanceName     = Configuration.GetSection("CacheProvider:Redis_InstanceName").Value
            };

            //判断是否使用Redis,如果不使用 Redis就默认使用 MemoryCache
            if (cacheProvider.IsUseRedis)
            {
                //Use Redis
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = cacheProvider.ConnectionString;
                    options.InstanceName  = cacheProvider.InstanceName;
                });
                services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
                {
                    Configuration = cacheProvider.ConnectionString,
                    InstanceName  = cacheProvider.InstanceName
                }, 0));
            }
            else
            {
                //Use MemoryCache
                services.AddSingleton <IMemoryCache>(factory =>
                {
                    var cache = new MemoryCache(new MemoryCacheOptions());
                    return(cache);
                });
                services.AddSingleton <ICacheService, MemoryCacheService>();
            }

            var jwtConfig = Configuration.GetSection("Jwt");
            var jwtOption = new JwtOption
            {
                Issuer         = jwtConfig["Issuer"],
                Expiration     = Convert.ToInt16(jwtConfig["Expiration"]),
                Secret         = jwtConfig["Secret"],
                Audience       = jwtConfig["Audience"],
                refreshJwtTime = Convert.ToInt16(jwtConfig["refreshJwtTime"])
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;;
            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    //NameClaimType = JwtClaimTypes.Name,
                    //RoleClaimType = JwtClaimTypes.Role,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtOption.Secret)),//秘钥
                    ValidateIssuer           = true,
                    ValidIssuer      = jwtOption.Issuer,
                    ValidateAudience = true,
                    ValidAudience    = jwtOption.Audience,
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(5)
                };
            });
            IoCContainer.Register(cacheProvider); //注册缓存配置
            IoCContainer.Register(Configuration); //注册配置
            IoCContainer.Register(jwtOption);     //注册配置
            services.AddScoped(typeof(SSOAuthHelper));
            services.AddScoped(typeof(AuthHelper));
            IoCContainer.Register("Yuebon.Commons");
            IoCContainer.Register("Yuebon.AspNetCore");
            IoCContainer.Register("Yuebon.Security.Core");
            IoCContainer.Register("Yuebon.Messages.Core");
            IoCContainer.RegisterNew("Yuebon.Security.Core", "Yuebon.Security");
            IoCContainer.RegisterNew("Yuebon.Messages.Core", "Yuebon.Messages");
            List <Assembly> myAssembly = new List <Assembly>();

            myAssembly.Add(Assembly.Load("Yuebon.Security.Core"));
            myAssembly.Add(Assembly.Load("Yuebon.Messages.Core"));
            services.AddAutoMapper(myAssembly);
            services.AddScoped <IMapper, Mapper>();
            return(IoCContainer.Build(services));
        }
 public RefreshTokenFactory(IOptions <JwtOption> jwtOption)
 {
     _jwtOption = jwtOption.Value;
 }