public async Task <IActionResult> Login([FromBody] LoginModel model)
        {
            try
            {
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

                if (result.Succeeded)
                {
                    var aspNetUser = await _userManager.FindByEmailAsync(model.UserName);

                    var role = await _userManager.GetRolesAsync(aspNetUser);

                    var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.UserName);
                    TokenOption          = new TokenOption();
                    TokenOption.Issuer   = _config["TokenOption:Issuer"];
                    TokenOption.Audience = _config["TokenOption:Audience"];
                    TokenOption.Key      = _config["TokenOption:Key"];
                    var expiry = _config["TokenOption:ExpireMinutes"];
                    TokenOption.ExpireMinutes = Convert.ToInt32(expiry);
                    return(Ok(Identity.Security.GenerateJwtToken(model.UserName, aspNetUser, TokenOption, role.FirstOrDefault())));
                }
                else
                {
                    return(Unauthorized(new { Code = (int)HttpStatusCode.Unauthorized, Message = _errorHandler.GetMessage(ErrorMessagesEnum.AuthWrongCredentials) }));
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #2
0
        /// <summary>
        /// 获取api token
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetJwtToken(TokenOption model)
        {
            var jwtBearerOption = EnginContext.Current.Resolve <IOptions <AppSettingOption> >();

            //创建用户身份标识,可按需要添加更多信息
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, model.ID.ToString()),
                new Claim(ClaimTypes.Sid, model.UserCode),  // 用户id
                new Claim(ClaimTypes.Name, model.UserName), // 用户名
                new Claim(ClaimTypes.Role, model.UserRole), // 是否是管理员
                new Claim(ClaimTypes.AuthorizationDecision, model.UserWork),
                new Claim(ClaimTypes.UserData, model.UserData)
            };

            var SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtBearerOption.Value.JwtBearer.SecurityKey));
            var Credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);

            //创建令牌
            var token = new JwtSecurityToken(
                issuer: jwtBearerOption.Value.JwtBearer.Issuer,
                audience: jwtBearerOption.Value.JwtBearer.Audience,
                signingCredentials: Credentials,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddSeconds(jwtBearerOption.Value.JwtBearer.ExpireSeconds)
                );

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwtToken);
        }
 public TokenHandler(IOptions <TokenOption> tokenOptionSnapshot, SigningConfigurations signingConfigurations, IHasher hasher, IUnitOfWork unitOfWork, RoleManager <ApplicationRole> roleManger, UserManager <ApplicationUser> userManger)
 {
     _tokenOptions          = tokenOptionSnapshot.Value;
     _hasher                = hasher;
     this.unitOfWork        = unitOfWork;
     _signingConfigurations = signingConfigurations;
     _roleManager           = roleManger;
     _userManager           = userManger;
 }
Exemple #4
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="content"></param>
        /// <param name="model"></param>
        public static void SignIn(this HttpContext content, TokenOption model, string scheme = CookieAuthenticationDefaults.AuthenticationScheme)
        {
            var claimIdentity = new ClaimsIdentity(scheme);

            claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.ID.ToString()));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Sid, model.UserCode));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Name, model.UserName));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Role, model.UserRole));
            claimIdentity.AddClaim(new Claim(ClaimTypes.AuthorizationDecision, model.UserWork));
            claimIdentity.AddClaim(new Claim(ClaimTypes.UserData, model.UserData));

            content.SignInAsync(scheme, new ClaimsPrincipal(claimIdentity), new AuthenticationProperties()
            {
                IsPersistent = true
            });
        }
Exemple #5
0
        public Startup(IHostingEnvironment env)
        {
            _env = env;
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            string secretKey   = "9661278F-4F9F-4424-A004-ABCA7EDF584E";
            var    tokenOption = new TokenOption
            {
                Audince  = "LocalServer",
                Issuer   = "LocalHost",
                Key      = secretKey,
                LifeTime = 30
            };

            _tokenOption = tokenOption;
        }
Exemple #6
0
        public static async Task <Authentication.TokenResult> RedeemAuthorizationCodeAsync(string clientId, string redirectUrl, string clientSecret, string authCode, string starturi, string granttype, TokenOption option)
        {
            QueryStringBuilder queryBuilder = new QueryStringBuilder();

            queryBuilder.Add("client_id", clientId);
            queryBuilder.Add("client_secret", clientSecret);
            if (!string.IsNullOrEmpty(redirectUrl))
            {
                queryBuilder.Add("redirect_uri", redirectUrl);
            }
            if (option == TokenOption.CODE)
            {
                queryBuilder.Add("code", authCode);
            }
            else
            {
                queryBuilder.Add("refresh_token", authCode);
            }
            queryBuilder.Add("grant_type", granttype);

            return(await PostToTokenEndPoint(queryBuilder, starturi));
        }
Exemple #7
0
        /// <summary>
        /// Create a token generator instance
        /// </summary>
        /// <param name="tokenOptions"></param>

        public JwtTokenGenerator(TokenOption tokenOptions)
        {
            this.tokenOptions = tokenOptions ??
                                throw new ArgumentNullException(
                                          $"An instance of valid {nameof(TokenOption)} must be passed in order to generate a JWT!");
        }
 public TokenProvider(IOptions <TokenOption> tokenOption)
 {
     _tokenOption = tokenOption.Value;
 }
Exemple #9
0
        public static TokenViewModel GenerateJwtToken(string email, ApplicationUser user, TokenOption options, string role
                                                      )
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Role, role),
                new Claim(ClaimTypes.Email, email)
            };

            DateTime TokenExpiry;

            TokenExpiry = DateTime.Now.AddMinutes(options.ExpireMinutes);

            var token = new JwtSecurityToken
                        (
                issuer: options.Issuer,
                audience: options.Audience,
                claims: claims,
                expires: TokenExpiry,
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Key)),
                                                           SecurityAlgorithms.HmacSha256)
                        );
            var response = new TokenViewModel
            {
                UserName = user.Email,
                Token    = new JwtSecurityTokenHandler().WriteToken(token),
                Expires  = TokenExpiry,
                Role     = role,
                NAME     = user.UserName,
                UserId   = user.Id,
                Phone    = user.PhoneNumber,
            };

            return(response);
        }