public async Task <TokenView> GenerateTokenAsync(User user, IEnumerable <Role> roles) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Uri, user.ImageUrl ?? string.Empty), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64) }; var roleClaims = roles.Select(role => new Claim(ClaimTypes.Role, role.Name)); var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims.Concat(roleClaims), notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var token = new JwtSecurityTokenHandler().WriteToken(jwt); return(new TokenView { Token = token }); }
public async Task <IActionResult> Post([FromBody] LoginModel logingUser) { // 驗證並取得使用者資訊 var identity = await GetClaimsIdentity(logingUser.Username, logingUser.Password); if (identity == null) { return(BadRequest("Invalid credentials")); } // 產生 JWT 並進行編碼 var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: new[] { new Claim(JwtRegisteredClaimNames.Sub, logingUser.Username), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("Role") }, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { accessToken = encodedJwt, expiresIn = (int)_jwtOptions.ValidFor.TotalSeconds }; return(new JsonResult(response)); }
private async Task <string> GenerateToken(LoginRequest request, User user, ICollection <Claim> userClaims) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, request.UserName), new Claim("username", request.UserName), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64) }; if (user.UserType > 0) { claims.Add(new Claim(_jwtOptions.CommonClaimName, user.UserType.ToString())); } claims.AddRange(userClaims.Select(c => new Claim(JwtOptions.ClaimAcessName, c.Type))); // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var tokenHandler = new JwtSecurityTokenHandler(); string encodedJwt = tokenHandler.WriteToken(jwt); _tokenCache.Add(jwt.Id); _logger.LogInformation(LoggingEvents.GenerateItems, "Generate the Token."); return(encodedJwt); }
public async Task <IActionResult> GetToken([FromBody] GetTokenRequest applicationUser) { var security = _securityRepository.GetSecurity(); if (security.ApiAccessDisabled) { _logger.LogWarning( "Api access is denied becasuse to many failed get token attempts. To enable access open manually Security.json file and set property ApiAccessDisabled to false. "); throw new HttpError(HttpStatusCode.Forbidden); } var identityTask = GetClaimsIdentity(applicationUser, security); var identity = await identityTask; if (identity == null) { _logger.LogInformation( $"Invalid username ({applicationUser.Username}) or password ({applicationUser.Password})"); _securityRepository.IncreaseFailedGetTokenAttempts(security); return(BadRequest("Invalid credentials")); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, applicationUser.Username), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response2 = new GetTokenResponse { Token = encodedJwt, ExpiresIn = (int)_jwtOptions.ValidFor.TotalSeconds }; return(Ok(response2)); }
public async Task <UserProfile> LoginAsync(LoginRequest request) { User user = await TryLoginAsync(request); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, request.UserName), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64) }; // add database name claim claims.Add(new Claim(_jwtOptions.InstanceClaimName, user.InstanceName)); // add user claims ICollection <Claim> userClaims = await _userManager.GetClaimsAsync(user); claims.AddRange(userClaims); // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var tokenHandler = new JwtSecurityTokenHandler(); string encodedJwt = tokenHandler.WriteToken(jwt); _tokenCache.Add(jwt.Id); // Serialize and return the response var response = new UserProfile { UserName = user.UserName, InstanceName = user.InstanceName, Access = userClaims.Select(c => c.Value).ToList(), Token = encodedJwt, TokenExpirationDate = DateTime.Now.AddSeconds((int)_jwtOptions.ValidFor.TotalSeconds) }; _logger.LogInformation("User logged in."); return(response); }
public async Task <string> GenerateToken(User user) { string role = (await UserManager.GetRolesAsync(user)).FirstOrDefault(); var identity = new ClaimsIdentity(new GenericIdentity(user.Id, "Token"), new[] { new Claim(Core.JWT_CLAIM_ID, user.Id), new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, await JwtOptions.JtiGenerator()), new Claim(Core.JWT_CLAIM_ROL, role), new Claim(Core.JWT_CLAIM_VERIFIED, user.PhoneNumberConfirmed.ToString()) }); /* * var claims = new[] * { * new Claim(JwtRegisteredClaimNames.Sub, user.UserName), * new Claim(JwtRegisteredClaimNames.Jti, await JwtOptions.JtiGenerator()), * new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(JwtOptions.IssuedAt).ToString()), * identity.FindFirst(Core.JWT_CLAIM_ID_ROL), * identity.FindFirst(Core.JWT_CLAIM_ID_ID), * identity.FindFirst(Core.JWT_CLAIM_ID_VERIFIED), * }; * * var jwt = new JwtSecurityToken( * issuer: JwtOptions.Issuer, * audience: JwtOptions.Audience, * claims: claims, * notBefore: JwtOptions.NotBefore, * expires: JwtOptions.Expiration, * signingCredentials: JwtOptions.SigningCredentials); * * var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); * return encodedJwt; */ return(new JwtSecurityTokenHandler().CreateEncodedJwt( JwtOptions.Issuer, JwtOptions.Audience, identity, JwtOptions.NotBefore, JwtOptions.Expiration, JwtOptions.IssuedAt, JwtOptions.SigningCredentials)); }
private async Task <List <Claim> > GetUserClaims(User user) { var role = user.Roles.First(); var needResetPassword = await IsNeedResetPassword(user.UserName); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, _jwtOptions.IssuedAt.DatetimeToUnixTimeStamp().ToString(CultureInfo.CurrentCulture), ClaimValueTypes.Integer64), new Claim(ClaimTypes.Role, role.Role.Name), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(CultureInfo.CurrentCulture)), new Claim(nameof(JsonWebTokenPayload.NeedResetPassword), JsonSerializer.Serialize(needResetPassword)), new Claim(CustomClaims.TokenIdClaim, Guid.NewGuid().ToString()) }; return(claims); }
/// <summary> /// 生成Token /// </summary> /// <param name="username">用户</param> /// <param name="identity">身份</param> /// <returns></returns> public async Task <string> GenerateToken(LoginRequestModel model) { try { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.NameId, model.NTID), new Claim(JwtRegisteredClaimNames.Sub, _jwtOptions.Subject), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, _jwtOptions.IssuedAt.ToString()) }; var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: await _jwtOptions.SigningCredentials() ); var encodeJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { auth_token = encodeJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds, token_type = "Bearer" }; return(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Post([FromBody] Usuario usuario) { var identity = await GetClaimsIdentity(usuario); if (identity == null) { return(BadRequest("Credenciales incorrectas")); } var claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Sub, usuario.Login), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), }; _jwtOptions.UpdateToken(); var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: DateTime.UtcNow, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
public async Task <string> GenerateEncodedToken(string userName, ClaimsIdentity identity) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userName), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst(Constants.JwtClaimIdentifiers.Rol), identity.FindFirst(Constants.JwtClaimIdentifiers.Id) }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
public async Task <IActionResult> Post(SigninVM model) { User _user = new User(); #region #1 帳密資訊驗證 if (model.ClientId == null) { return(new BadRequestObjectResult("invalid_clientid: Please provide 'Client ID'.")); } var audience = db.Audiences.Where(x => x.AudienceId == model.ClientId); if (audience == null) { return(new BadRequestObjectResult($"invalid_clientid: Client ID '{model.ClientId}' is isvalid.")); } //取得 Jwt 過程中的帳號與密碼驗證 if (string.IsNullOrEmpty(model.Account) || string.IsNullOrEmpty(model.Password)) { return(new BadRequestObjectResult($"invalid_clientid: Account or password is incorrect.")); } else { _user = db.Users.Single(x => x.Account == model.Account && x.Password == model.Password); //使用者資訊驗證 if (_user == null) { return(new BadRequestObjectResult($"invalid_clientid: Account or password is incorrect.")); } } #endregion #region #2 資訊驗證成功,建立 Identity //取出帳號所屬角色資訊 List <Claim> role_claim = new List <Claim>(); if (_user.Roles != null && _user.Roles.Count() > 0) { foreach (var r in _user.Roles) { role_claim.Add(new Claim(ClaimTypes.Role, r)); } } //建立 Identity.Claim ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(model.Account, "Token"), new[] { //new Claim("IsValidAuthorized", "true"), new Claim("Uid", _user.Account), new Claim("Account", _user.Account), new Claim("Username", _user.Name), }.Concat(role_claim)); #endregion #region #3 發放 Token //設定 Token 記載內容 double unixEpocDate = Math.Round((_jwtOptions.IssueAt.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalSeconds); var claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Aud, model.ClientId), new Claim(JwtRegisteredClaimNames.Sub, model.Account), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, unixEpocDate.ToString(), ClaimValueTypes.Integer64), }; claims.AddRange(identity.Claims); //生成 Jwt token, 並進行編碼 var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials ); string encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); //回傳 Token var response = new { access_token = encodedJwt, token_type = "bearer", expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; return(new OkObjectResult(response)); #endregion }