public LonginResult Login(LoginModel model) { return(new LonginResult { token = _jwtHelper.GenerateToken(model.UserName, 20) }); }
public async Task <ActionResult <string> > SignIn(LoginViewModel login) { if (await ValidateUserAsync(login)) { return(jwt.GenerateToken(login.UserName)); } else { return(BadRequest()); } }
public JsonResult Refresh([FromBody] AppTokenModel refreshModel) { var token = refreshModel.AccessToken; var refreshToken = refreshModel.RefreshToken; var principal = JwtHelper.GetPrincipalFromExpiredToken(token); var username = principal.Identity.Name; var savedRefreshToken = _refreshTokenRepository.Get(username); //retrieve the refresh token from a data store if (savedRefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } var newJwtToken = JwtHelper.GenerateToken(principal.Claims); var newRefreshToken = RefreshTokenHelper.GenerateRefreshToken(); _refreshTokenRepository.Delete(username, refreshToken); _refreshTokenRepository.Save(username, newRefreshToken); return(Json(new AppTokenModel { AccessToken = newJwtToken, RefreshToken = newRefreshToken })); }
private async Task <ReturnDto> Auth(VerifyEnum authority, AuthorityModel model) { ReturnDto ret; var authorities = _issuers["owner"].Authorities; string token = model.token; if (string.IsNullOrWhiteSpace(token)) { token = JwtHelper.GenerateToken(new Claim[] { }, 60); } var principle = JwtHelper.GetClaimsPrincipal(token); if (principle?.Identity?.IsAuthenticated == true) { try { var claimsIdentity = principle.Identity as ClaimsIdentity; var verifyResult = _issuers["owner"].Verify(authority, claimsIdentity.Claims.ToArray(), model.payload); ret = await ResultFactory(authority, verifyResult); return(ret); } catch (Exception exc) { ret = ExceptionReturn(exc); return(ret); } } return(TokenNotValid()); }
public async Task <IActionResult> RefreshToken([FromQuery] string token) { var user = await _userService.GetUserByToken(token); if (user == null) { return(Ok(new { message = "User not found." })); } var ipAddress = await HttpHelper.GetIP4Address(HttpContext); var response = await JwtHelper.GenerateRefreshToken(ipAddress); if (response == null) { return(Unauthorized(new { message = "Invalid token" })); } var newToken = await JwtHelper.GenerateToken(user, _setting); await _userService.RefreshToken(token, ipAddress, newToken); return(Ok(new UserResponse { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Token = newToken })); }
public object loginAccount(dynamic dy) { //获取账户名名称 string accountName = dy.accountName.ToString(); //获取账户密码 string accountPwd = dy.accountPwd.ToString(); try { var account = new { AccountName = "admin", AccountPwd = "123456" }; if (accountName.Equals(account.AccountName) && accountPwd.Equals(account.AccountPwd)) { //声明 用于创建临牌的参数(自己想加些什么参数就什么) Claim[] claims = new Claim[] { new Claim("accountName", accountName.ToString()), new Claim("accountPwd", accountPwd.ToString()) }; //调用 Jwthelper 类来创建令牌 string token = JwtHelper.GenerateToken(claims); //返回令牌 return(new { code = 200, message = "登录成功!", data = new { token, accountName, accountPwd } }); } else { return(new { code = 200, message = "账号或密码错误!" }); } } catch (Exception ex) { throw ex; } }
public IActionResult Refresh(TokenTransferDTO tokens) { var jwtHelper = new JwtHelper(); List <Claim> claims; Guid userId; try { claims = jwtHelper.GetClaimsFromExpiredToken(tokens.Token); userId = Guid.Parse(claims.First(claim => claim.Type == "userId").Value); } catch (Exception) { return(Forbid()); } var savedRefreshToken = _userRepository.GetRefreshTokens(userId); //retrieve the refresh token from a data store if (savedRefreshToken.All(rt => rt.Value != tokens.RefreshToken)) { throw new SecurityTokenException("Invalid refresh token"); } var newJwtToken = jwtHelper.GenerateToken(claims); var newRefreshToken = jwtHelper.GenerateRefreshToken(); _userRepository.DeleteRefreshToken(userId, tokens.RefreshToken); _userRepository.SaveRefreshToken(userId, newRefreshToken); return(new ObjectResult(new { token = newJwtToken, refreshToken = newRefreshToken })); }
public async Task <LoginResult> Login() { //List of standard Payload claims https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields var ParametersByte = await Request.GetRawBodyBytesAsync(); var LoginParameters = RestApiDataStore.GetObjectsFromByteArray <LoginParameters>(ParametersByte); if (LoginParameters.Username == "Joche" && LoginParameters.Password == "123") { JwtPayload InitialPayload; InitialPayload = new JwtPayload { { JwtRegisteredClaimNames.NameId, LoginParameters.Username }, { JwtRegisteredClaimNames.Iat, JwtHelper.ConvertToUnixTime(DateTime.Now).ToString() }, { JwtRegisteredClaimNames.Iss, Issuer }, }; var StringToken = JwtHelper.GenerateToken(Key, InitialPayload); return(new LoginResult() { Authenticated = true, Token = StringToken }); } else { return new LoginResult() { Authenticated = false, Token = "" } }; } }
public JsonResult Token([FromBody] Form form) { var username = form.UserName; var password = form.Password; var identity = GetIdentity(username, password); if (identity == null) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json("Invalid username or password.")); } var encodedJwt = JwtHelper.GenerateToken(identity.Claims); var refreshToken = RefreshTokenHelper.GenerateRefreshToken(); _refreshTokenRepository.Delete(username); _refreshTokenRepository.Save(username, refreshToken); var response = new AppTokenModel { AccessToken = encodedJwt, RefreshToken = refreshToken, Username = identity.Name }; return(Json(response)); }
/// <summary> /// 用户是否存在 /// </summary> /// <param name="staff"></param> /// <param name="phoneNumber"></param> /// <returns></returns> private Response User_login(dynamic staff, string phoneNumber) { var token = JwtHelper.GenerateToken((int)staff["FID"], (string)staff["FJOB"], 2); var user = new { userId = (int)staff["FID"], wxopenid = (string)staff["FWXOPENID"], FJOB = (string)staff["FJOB"], userName = (string)staff["FNAME"], channelName = (string)staff["CHANNELNAME"], channelCode = (string)staff["FCHANNELCODE"], channelId = (int)staff["FCHANNELID"], customerId = (int)staff["FCUSTOMERID"], channelTypeId = (int)staff["FCHANNELTYPEID"], channelTypeName = (string)staff["FCHANNELTYPENAME"], avatarUrl = (string)staff["PICTURE"], nickName = (string)staff["KHNAME"], phoneNumber = phoneNumber }; return(new Response { Result = new { token, user } }); }
public async Task <IActionResult> Account(string authority, [FromBody] AuthorityModel model) { if (model == null || model?.payload == null) { return(Unauthorized()); } var authorities = _issuers["owner"].Authorities; if (!authorities.Any()) { return(Unauthorized()); } string token = model.token; if (string.IsNullOrWhiteSpace(authority)) { authority = authorities.Keys.ToArray()[0]; token = JwtHelper.GenerateToken(new Claim[] { }, _settings.Value.AwronoreSettings.OtpTimeOut); } if (string.IsNullOrWhiteSpace(token)) { return(Unauthorized()); } var principle = JwtHelper.GetClaimsPrincipal(token); if (principle?.Identity?.IsAuthenticated == true) { try { var claimsIdentity = principle.Identity as ClaimsIdentity; var(verifyResult, otp) = await _issuers["owner"].VerifyAsync(authority, claimsIdentity.Claims.ToArray(), model.payload); if (verifyResult.Authority == null) { return(Ok(new { auth_token = verifyResult.Token })); } return(Ok(new { verify_token = verifyResult.Token, authority = verifyResult.Authority, parameters = verifyResult.Payload, otp = "", timeOut = _settings.Value.AwronoreSettings.OtpTimeOut })); } catch (Exception e) { if (e is AwronoreIdentityException) { throw e; } return(Unauthorized()); } } return(Unauthorized()); }
public async Task <IActionResult> Auth(LoginDto dto) { var user = await UserManager.FindByEmailAsync(dto.Email); if (user == null) { return(BadRequest()); } var result = await _signInManager.CheckPasswordSignInAsync(user, dto.Password, false); if (!result.Succeeded) { return(BadRequest()); } var expiration = 30; var token = JwtHelper.GenerateToken( user, Environment.GetEnvironmentVariable(EnvVars.JwtKey), Configuration["JwtTokenConfig:Issuer"], Configuration["JwtTokenConfig:Audience"], expiration); var refreshToken = _tokenFactory.GenerateRefreshToken(); user.AddRefreshToken(refreshToken, 10); await DbContext.SaveChangesAsync(); return(Ok(new LoginResultDto("Bearer", token, refreshToken, DateTime.Now.AddDays(expiration), user.UserType, user.Name))); }
public async Task <LoginResponseModel> LoginAsync(LoginUserModel loginUserModel) { var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == loginUserModel.Username); if (user == null) { throw new NotFoundException("Username or password is incorrect"); } var signInResult = await _signInManager.PasswordSignInAsync(user, loginUserModel.Password, false, false); if (!signInResult.Succeeded) { throw new BadRequestException("Username or password is incorrect"); } var token = JwtHelper.GenerateToken(user, _configuration); return(new LoginResponseModel { Username = user.UserName, Email = user.Email, Token = token }); }
public async Task <IActionResult> Post(RefreshTokenDto dto) { var handler = new JwtSecurityTokenHandler(); var cp = handler.ReadJwtToken(dto.OldJwtToken); if (string.IsNullOrEmpty(cp.Id)) { var user = await UserManager.FindByIdAsync(cp.Payload.Claims.FirstOrDefault (x => x.Type.Equals(JwtRegisteredClaimNames.Sid)).Value); if (user != null && user.RefreshToken.Equals(dto.RefreshToken) && user.RefreshTokenExpiration >= DateTime.Now) { var expiration = 30; var token = JwtHelper.GenerateToken( user, Environment.GetEnvironmentVariable(EnvVars.JwtKey), Configuration["JwtTokenConfig:Issuer"], Configuration["JwtTokenConfig:Audience"], expiration); var refreshToken = _tokenFactory.GenerateRefreshToken(); user.AddRefreshToken(refreshToken, 10); await DbContext.SaveChangesAsync(); return(Ok(new LoginResultDto("Bearer", token, refreshToken, DateTime.Now.AddDays(expiration), user.UserType, user.Name))); } } AddMessage("Token", "Token inválido"); return(BadRequest()); }
public TokenResponse CreateToken(ClientKeyVm key) { // Grab all the resource access of the client // we'll be using that to create claims to be passed to our // JWT generator. var dataAccess = ResourceUnitOfWork.ClientSvc.GetClientResourceAccess(key.ClientId); if (dataAccess == null) { return(null); } JwtHelper tokenizer = new JwtHelper(APIToken); var identity = new ClaimsIdentity(); identity.AddClaim(new Claim(ClaimTypes.Name, key.APIKey)); foreach (var access in dataAccess) { identity.AddClaim(new Claim(SharedClaimType.DataAccess, access.ResourceId.ToString())); } var token = tokenizer.GenerateToken(identity); return(new TokenResponse() { ExpireDate = token.ExpireDate, Token = token.Token }); }
public async Task <AuthResponseVM> Handle(RegisterCommand request, CancellationToken cancellationToken) { var response = new AuthResponseVM(); var user = new User { Email = request.Email, UserName = request.Email }; var result = await userManager.CreateAsync(user, request.Password); if (!result.Succeeded) { response.Errors = result.Errors.Select(c => c.Description).ToList(); return(response); } var role = roleManager.Roles.FirstOrDefault(c => c.Name == "Customer"); await userManager.AddToRoleAsync(user, role.Name); var token = await JwtHelper.GenerateToken(user, jwtSettings.Secret, userManager); response.Token = token; response.Email = user.Email; return(response); }
public HttpResponseMessage CheckLogin(JObject postData) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); try { string _userCode = postData["UserCode"].ToString(); string _password = postData["Password"].ToString(); string _token = JwtHelper.GenerateToken(_userCode); Dictionary <string, object> result = new Dictionary <string, object>() { { "Status", "Ok" }, { "Token", _token } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(result); httpResponseMessage.Content = new StringContent(json); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpResponseMessage.Headers.Add("Authorization", _token); RedisClient redis = new RedisClient("192.168.197.132", 6379); redis.Set(_userCode, _token); return(httpResponseMessage); } catch (Exception ex) { return(null); } }
public async Task <string> RefreshToken() { string userName = await Operator.Instance.GetCurrent(); User user = await EFDB.Create().FindAsync <User>(x => x.UserName == userName); return(JwtHelper.GenerateToken(user, GlobalInvariant.SystemConfig.JwtConfig)); }
private AuthenticationLoginResponseDto CreateDtoWith(UserEntity userEntity) { var response = new AuthenticationLoginResponseDto(); response.Name = userEntity.Name; response.Token = _jwtHelper.GenerateToken(userEntity); return(response); }
public async Task<LoginResult> Login() { //List of standard Payload claims https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields byte[] ParametersByte = await Request.GetRawBodyBytesAsync(); LoginParameters LoginParameters = RestApiDataStore.GetObjectsFromByteArray<LoginParameters>(ParametersByte); string Database; string Server; Employee User = null; try { string UserName = WebUtility.UrlDecode(LoginParameters.Username); string Password = WebUtility.UrlDecode(LoginParameters.Password); Server = WebUtility.UrlDecode(LoginParameters.Server); Database = WebUtility.UrlDecode(LoginParameters.Database); UnitOfWork UoW = XpoProxyHelper.GetUnitOfWork(Database, Server); User = UoW.FindObject<Employee>(new BinaryOperator("UserName", UserName)); if (User == null) { return new LoginResult() { Authenticated = false, Token = "" }; } if (!User.ComparePassword(Password)) { return new LoginResult() { Authenticated = false, Token = "" }; //TODO invalid password } } catch (Exception exception) { return new LoginResult() { Authenticated = false, Token = "", ErrorMessage= exception.Message }; } JwtPayload InitialPayload; InitialPayload = new JwtPayload { { JwtRegisteredClaimNames.NameId, LoginParameters.Username }, { JwtRegisteredClaimNames.Iat, JwtHelper.ConvertToUnixTime(DateTime.Now).ToString() }, { JwtRegisteredClaimNames.Iss, Issuer }, { "DatabaseId", Database }, { "ServerId", Server }, }; var StringToken = JwtHelper.GenerateToken(Key, InitialPayload); return new LoginResult() { Authenticated = true, Token = StringToken, CurrentUserId = User?.Oid.ToString()}; }
public async Task <(IssuerVerifyResult, string otp)> VerifyAsync(string authority, Claim[] claims, JObject payload) { var verifyAuthority = _authorities[authority]; var verifyClaims = verifyAuthority.OnVerify(claims, payload, _identifier, out bool valid); var authorities = _authorities.Values.ToList(); var idx = authorities.IndexOf(verifyAuthority); string otp = ""; if (idx < _authorities.Count - 1) { var nextAuthority = authorities[idx + 1]; var forwardClaims = new Claim[] { }; var forwardAuthority = _authorities.Keys.ElementAt(idx + 1); var forwardPayload = nextAuthority.Payload; if (verifyClaims.Any()) { var(claimsList, otpcode) = await nextAuthority.OnForwardAsync(verifyClaims); otp = otpcode; //forwardClaims = nextAuthority.OnForward(verifyClaims); forwardClaims = claimsList; } if (valid) { var verifyToken = JwtHelper.GenerateToken(verifyClaims.Concat(forwardClaims).ToArray(), _timeouts[authority]); return(new IssuerVerifyResult() { Token = verifyToken, Authority = forwardAuthority, Payload = forwardPayload }, otp); } } else { if (valid) { var identifier = verifyClaims.SingleOrDefault(c => c.Type == _identifier); var authenticationClaims = _authenticator.GetAuthenticationClaims(identifier.Value); return(new IssuerVerifyResult() { Token = JwtHelper.GenerateToken(authenticationClaims, _timeouts[authority]), Authority = null, Payload = null }, otp); } } var token = JwtHelper.GenerateToken(verifyClaims, _timeouts[authority]); return(new IssuerVerifyResult() { Token = token, Authority = authority, Payload = verifyAuthority.Payload }, otp); }
/// <summary> /// 生成访客token /// </summary> /// <returns></returns> public Response GenerateGuestToken() { var newToken = JwtHelper.GenerateToken(0, "guest", 2); return(new Response { Result = newToken }); }
public void TestValidateToken_Invalid_TestExpiryTime() { int lifespanInSeconds = 10; TestToken = JwtHelper.GenerateToken(claimsPrincipal.Claims, TestAudience, lifespanInSeconds); Thread.Sleep(1000 * (lifespanInSeconds + 1)); var result = JwtHelper.GetPrincipal(TestToken); Assert.IsNull(result); }
public void Setup() { claimsPrincipal = new ClaimsPrincipal(); claimsPrincipal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim(CLAIM_TYPE_USER_ID, "9999"), new Claim(CLAIM_TYPE_RECORD_ID, "123456") }));; TestToken = JwtHelper.GenerateToken(claimsPrincipal.Claims, TestAudience); }
public IssuerVerifyResult Register(IDictionary <VerifyEnum, IAuthority> authorities, Claim[] verifyClaims, string _identifier, int timeout) { var identifier = verifyClaims.FirstOrDefault(c => c.Type == _identifier); var authenticationClaims = _authenticator.GetAuthenticationClaims(identifier.Value); return(new IssuerVerifyResult() { Token = JwtHelper.GenerateToken(authenticationClaims, timeout), }); }
/// <summary> /// Sets a new JWT to authenticate via HTTP to the Authorization Header of the Client object /// </summary> /// <param name="userType">The UserType you want to authenticate as</param> public void SetToken(UserType userType) { //If we already have generated a token for this UserType, use it and return if (JWTs.ContainsKey(userType)) { Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWTs[userType]); return; } string userName; string roleName; //Start by getting the corresponding UserName and Role switch (userType) { case UserType.Administrator: { userName = AdminUserName; roleName = AdministratorRoleName; } break; case UserType.UserManager: { userName = ManagerUserName; roleName = UserManagerRoleName; } break; case UserType.Regular: { userName = RegularUserName; roleName = RegularUserRoleName; } break; default: throw new NotImplementedException($"UserType {userType} has not been implemented."); } //Generate the Token string jwt = JwtHelper.GenerateToken( Configuration["Secret"], userName, roleName, DateTime.UtcNow.AddMinutes(10)); //Set the Authorization header of the Client Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); //Add the Token to the Dictionary JWTs.Add(userType, jwt); }
/// <summary> /// 构造返回的数据 /// </summary> /// <param name="sysUser"></param> /// <returns></returns> public GetAccessTokenResponse GetAccessTokenResponse(SysUser sysUser) { var token = JwtHelper.GenerateToken(sysUser.UserId, out DateTime expiresTime); var accessToken = new GetAccessTokenResponse() { AccessToken = $"Bearer {token}", ExpiresIn = SystemConfig.AuthenticationConfig.ExpiresHours * 3600 - 600 }; return(accessToken); }
public ActionResult <string> SignIn(LoginModel login) { if (ValidateUser(login)) { return(jwt.GenerateToken(login.Username)); } else { return(BadRequest()); } }
public string Get(string email, string password) { var user = _userService.GetAuthenticateUser(email, password); if (user != null) { return(JwtHelper.GenerateToken(email)); } throw new HttpResponseException(HttpStatusCode.Unauthorized); }
public async Task <ActionResult <string> > SignIn([FromForm] LoginViewModel login) { if (await userService.ValidateUserAsync(login)) { return(jwt.GenerateToken(login.Username)); } else { return(BadRequest()); } }