public UserDto Login([FromBody] LoginDto loginDto) { if (loginDto == null) { throw new UnauthorizedAccessException(); } var user = _usersRepository.GetUserByUsername(loginDto.Username); if (user == null) { throw new UnauthorizedAccessException(); } if (!user.ValidatePassword(loginDto.Password)) { throw new UnauthorizedAccessException(); } var tokenDto = _mapper.Map <SessionDto>(user); tokenDto.SessionId = _sessionRepository.NewSession(user.Id); tokenDto.ExpirationTime = DateTime.UtcNow.AddMinutes(AuthFilter.SessionLength); this.Response.Cookies.Append(AuthFilter.TokenHeader, JwtHelper.Encode(tokenDto), new CookieOptions() { Secure = true, HttpOnly = true }); return(_mapper.Map <UserDto>(user)); }
/// <summary> /// 换取登录token /// </summary> /// <param name="userId"></param> /// <param name="userName"></param> /// <returns></returns> public string ConvertLoginToken(int userId, string userName) { return(JwtHelper.Encode(new UserApiTokenPayload() { UserId = userId, UserName = userName }, _api_key_token)); }
public void TokenCheckFailTest() { var token = JwtHelper.Encode(new SessionDto()); var authorizationFilterContext = new AuthorizationFilterContext(new ActionContext(new TestHttpContext(), new RouteData(), new ActionDescriptor(), new ModelStateDictionary()), new List <IFilterMetadata>()); ((TestCoockieCollection)authorizationFilterContext.HttpContext.Request.Cookies).Add(AuthFilter.TokenHeader, token); new AuthFilter(GetService <ISessionRepository>(), GetService <IUsersRepository>(), new SessionDto()).OnAuthorization(authorizationFilterContext); Assert.IsTrue(authorizationFilterContext.Result is ForbidResult); }
public string Authenticate(string username, string password) { var user = _userRepository.GetUserByCredentials(username, PasswordHelper.HashPassword(password)); if (user == null) { throw new Exception("Wrong credentials"); } return(JwtHelper.Encode(JwtHelper.ContextFromUser(user))); }
protected virtual IHttpActionResult Logout(IDictionary <string, object> jwtPayload) { if (ExpiredMinutes > 0) { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); jwtPayload[JwtClaimName.exp.ToString()] = secondsSinceEpoch + ExpiredMinutes * 60; } string data = JwtHelper.Encode(jwtPayload, Secret); return(Succeed(data, "已经退出登陆")); }
protected virtual IHttpActionResult Login(string userName, string password) { if (VerifyLogin(userName, password, out IDictionary <string, object> jwtPayload)) { if (ExpiredMinutes > 0) { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); jwtPayload[JwtClaimName.exp.ToString()] = secondsSinceEpoch + ExpiredMinutes * 60; } string data = JwtHelper.Encode(jwtPayload, Secret); return(Succeed(data, "获取访问令牌成功")); } return(Fail("用户标识或密码错误")); }
public ResultDataWrapper <UserInfo> Login(DTO.LoginInput parameter) { this.CurrentUser.UserInfo = UserInfo.lstUserInfo.Where(x => x.LoginName == parameter.LoginName) .Where(x => x.Pwd == parameter.Pwd) .FirstOrDefault(); if (this.CurrentUser.UserInfo == null) { throw new HaishanException("用户名或密码错误"); } this.CurrentUser.JwtData = new JwtData() { Id = this.CurrentUser.UserInfo.Id, CreateDateTime = DateTime.Now }; var token = JwtHelper.Encode(this.CurrentUser.JwtData); var rt = ResultDataWrapper.Ok(this.CurrentUser.UserInfo); rt.SetToken(token); return(rt); }
// POST api/<controller> public HttpResponseMessage Post([FromBody] LoginRequest loginRequest) { LoginResponse loginResponse = null; var statusCode = System.Net.HttpStatusCode.OK; try { _logger.Info("Starting Api/Login POST"); using (var session = NHibernateHelper.CreateSessionFactory()) { using (var transaction = session.BeginTransaction()) { _logger.Info("Inside session and transaction"); // does this user exist? (db-call) _logger.Info("About to select user from database"); var users = session.CreateCriteria(typeof(User)).List <User>(); var user = users.FirstOrDefault(x => x.Username == loginRequest.Username); _logger.Info("Selected user from users table"); if (user != null) { _logger.Info("User does exist"); // if yes, validate him (db-call) var isValid = user.Password.Equals(loginRequest.Password); // is it correct? if (isValid) { _logger.Info("Password is correct"); // create a hash var token = JwtHelper.Encode(user.Id, user.Username, user.State.Id); _logger.Info("Generated token: " + token); // return success w/ hash to user loginResponse = new LoginResponse { StatusCode = 3, Reason = "Login success", Username = loginRequest.Username, Token = token }; } else { _logger.Info("User does not exist"); // no, tell him its wrong password loginResponse = new LoginResponse { StatusCode = 1, Reason = "The password is incorrect. Please try again", Username = loginRequest.Username }; } } else { // if no // tell him this user doesnt exist loginResponse = new LoginResponse { StatusCode = 2, Reason = "This username is not on the system. Please try again, or register if you don't have an account", Username = loginRequest.Username }; } } } //end using session if (loginResponse.StatusCode != 3) { statusCode = System.Net.HttpStatusCode.Unauthorized; } _logger.Info("About to return login response"); return(WebApiHelper.ObjectToHttpResponseMessage(loginResponse, statusCode)); } catch (Exception ex) { _logger.Error(ex.Message + ex.StackTrace + ex.InnerException); } _logger.Warn("Api/Login returned null"); return(WebApiHelper.ObjectToHttpResponseMessage(loginResponse, statusCode)); }