public IActionResult Login([FromBody] LoginRequest request) { try { if (string.IsNullOrWhiteSpace(request.Email)) { return(BadRequest("Invalid e-mail")); } if (string.IsNullOrWhiteSpace(request.Pass)) { return(BadRequest("Invalid password")); } var user = _repository.GetByEmail(request.Email); //TODO: Compare passwords { if (user?.CryptPass != request.Pass) { return(BadRequest("Invalid e-mail or password")); } } var token = _jwt.GenerateToken(user.Id); return(Ok(token)); } catch (Exception) { throw; } }
public IActionResult Login(string userName, string password) { LoginResponseStruct loginResponse = new LoginResponseStruct(); try { var userLogic = BLFactoryService.GetUserLogic; if (userLogic.IsUserExist(userName) && userLogic.IsUserValid(userName, password) ) { var user = userLogic.GetUser(userName); user.Password = ""; loginResponse.TokenDetails = JwtService.GenerateToken(user); loginResponse.User = user; } else { return(Unauthorized("InvalidUserDetails")); } } catch (SystemException e) { return(StatusCode(500, e)); } catch (Exception) { return(BadRequest()); } return(Ok(loginResponse)); }
public void GenerateToken_ValidParams_ShouldNotFail() { var jwt = new JwtService(key); var token = jwt.GenerateToken(); Assert.False(string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token)); }
public async Task <IActionResult> Login([FromBody] LoginUserViewModel model) { if (!ModelState.IsValid) { return(BadRequest()); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(NotFound()); } var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { var roles = await _userManager.GetRolesAsync(user); return(Ok(_jwtService.GenerateToken(user, roles))); } return(BadRequest()); }
public async Task <IActionResult> Register([FromBody] RegisterUserViewModel model) { if (!ModelState.IsValid) { return(BadRequest()); } var user = new IdentityUser { UserName = model.Email, Email = model.Email, EmailConfirmed = true }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, Roles.USER); var roles = await _userManager.GetRolesAsync(user); var appUser = new User(Guid.Parse(user.Id), model.Name, Roles.USER); await _userRepository.Add(appUser); return(Ok(_jwtService.GenerateToken(user, roles))); } return(BadRequest()); }
public void JwtValidationResultIndexer_RetrieveMultipleClaims_ShouldSucceed() { var jwt = new JwtService(key, clockSkew: TimeSpan.FromMinutes(3)); var token = jwt.GenerateToken( lifetime: TimeSpan.FromHours(1), claims: new[] { new Claim("claim1", "value1"), new Claim("claim2", "value2"), new Claim("claim3", "value3") } ); var result = jwt.ValidateToken(token); Assert.True(result.Successful); var claim1 = result["claim1"]; var claim2 = result["claim2"]; var claim3 = result["claim3"]; Assert.NotNull(claim1); Assert.NotNull(claim2); Assert.NotNull(claim3); Assert.Equal("claim1", claim1.Type); Assert.Equal("value1", claim1.Value); Assert.Equal("claim2", claim2.Type); Assert.Equal("value2", claim2.Value); Assert.Equal("claim3", claim3.Type); Assert.Equal("value3", claim3.Value); }
public void GenerateToken_ValidateMultipleClaims_ShouldSucceed() { var jwt = new JwtService(key, validateLifetime: false ); var claims = new[] { new Claim("claim1", "value1"), new Claim("claim2", "value2"), new Claim("claim3", "value3"), }; var token = jwt.GenerateToken( claims: claims ); foreach (var claim in jwt.ValidateToken(token).ValidatedToken.Item1.Claims) { Assert.Contains(claims, c => c.Type == claim.Type && c.Value == claim.Value && c.ValueType == claim.ValueType ); } }
public async Task <IActionResult> PostUser([Required][FromBody] Users body) { try { if (body.Password.Length < 8) { return(new BadRequestObjectResult("Password is too short")); } if (_context.Users.FirstOrDefault(x => x.Email == body.Email) != null) { return(new BadRequestObjectResult("Given email is already used")); } body.Password = SecurePasswordHasher.Hash(body.Password); var user = _context.Users.Add(body).Entity; _context.SaveChanges(); IAuthContainerModel model = JwtFunctions.GetJwtContainerModel(user.Id, user.Email); IAuthService authService = new JwtService(model.SecretKey); var token = authService.GenerateToken(model); return(new OkObjectResult(new { token, expiresIn = model.ExpireMinutes, user = _mapper.Map <DTOUserModel>(user) })); } catch (Exception ex) { return(new BadRequestObjectResult(new { error = ex, body })); } }
public ActionResult Login(MembersLoginViewModel LoginMember) { string ValidateStr = membersService.LoginCheck(LoginMember.Account, LoginMember.Password); if (String.IsNullOrEmpty(ValidateStr)) { //無錯誤訊息,則登入 //先藉由Service取得登入者角色資料 string RoleData = membersService.GetRole(LoginMember.Account); //設定JWT JwtService jwtService = new JwtService(); //從Web.Config撈出資料 //Coolie名稱 string cookieName = WebConfigurationManager.AppSettings["CookieName"].ToString(); string Token = jwtService.GenerateToken(LoginMember.Account, RoleData); //產生一個Cookie HttpCookie cookie = new HttpCookie(cookieName); //設定單值 cookie.Value = Server.UrlEncode(Token); //寫到用戶端 Response.Cookies.Add(cookie); //設定cookie期限 Response.Cookies[cookieName].Expires = DateTime.Now.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["ExpireMinutes"])); return(RedirectToAction("Index", "Home")); } else { //有驗證錯誤信息,加入頁面模型中 ModelState.AddModelError("", ValidateStr); return(View(LoginMember)); } }
public ActionResult Login(LoginModel model) { var userInfo = UsersRepository.FirstOrDefault(u => u.Login == model.Login, u => new { u.Password, u.Login, u.Id, u.DisplayName }); if (userInfo is null || PasswordHashingService.Hash(model.Password) != userInfo.Password) { return(Unauthorized("Login or password is incorrect.")); } var token = JwtService.GenerateToken(new[] { new Claim("login", userInfo.Login), new Claim("id", userInfo.Id.ToString()), new Claim("isAdministrator", (ContextProvider.Context == ContextType.Admin).ToString()), }, DateTime.UtcNow.AddMinutes(30)); Logger.LogInformation($"User got {token} token."); return(Ok(new { Token = token, model.ReturnUrl, userInfo.Login, userInfo.DisplayName, userInfo.Id })); }
public ActionResult SignIn(SigninViewModel member) { string Validatestr = memberservice.SigninCheck(member.Account, member.Password); if (String.IsNullOrEmpty(Validatestr)) { string RoleData = memberservice.GetRole(member.Account); JwtService jwtService = new JwtService(); string CookieName = WebConfigurationManager.AppSettings["CookieName"].ToString(); string Token = jwtService.GenerateToken(member.Account, RoleData); HttpCookie cookie = new HttpCookie(CookieName); cookie.Value = Server.UrlEncode(Token); Response.Cookies.Add(cookie); Response.Cookies[CookieName].Expires = DateTime.Now.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["ExpireMinutes"])); return(RedirectToAction("Index", "Platform")); } else { ModelState.AddModelError("", Validatestr); return(View(member)); } }
public void GenerateToken_OnlyPublicKeyProvided_ShouldFail() { using (var rsa = RSA.Create(4096)) { var jwt = new JwtService(rsa.ExportParameters(false)); Assert.Throws <ArgumentException>(() => { jwt.GenerateToken(); }); } }
public void GenerateAsymmetricJwtCorrectly_ShouldSucceed(int keySize) { using (var rsa = RSA.Create(keySize)) { var jwt = new JwtService(rsa.ExportParameters(true)); var token = jwt.GenerateToken(); Assert.False(string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token)); } }
public IActionResult Login(LoginInputModel model) { var response = service.Validate(model.Correo, model.Contraseña); return((response.Error) ? StatusCode(response.CodigoHttp, response) : StatusCode(response.CodigoHttp, new Respuesta <LoginViewModel>(_jwtService.GenerateToken(response.Objeto), response.CodigoHttp))); }
public async Task Token_For_Grant_Type_Refresh_Token_Should_Return_Valid_Token() { var jwtService = new JwtService() { Configuration = OAuthApiTestStartup.Configuration, Logger = new FakeLogger(), RepositoriesFactory = null, StringLocalizerFactory = new FakeStringLocalizerFactory() }; var jwtTokenDto = jwtService.GenerateToken(new CreateTokenDto() { ClientPublicId = _sammyClientPublicIdConfidential, Scope = _sammyScopeWording, SecondsLifeTime = OAuthApiTestStartup.Configuration.RefreshTokenLifeTimeInSeconds, TokenName = OAuthConvention.RefreshToken, UserName = _sammyUserName }); using (var context = new DaOAuthContext(_dbContextOptions)) { var userClient = context.UsersClients. FirstOrDefault(uc => uc.User.UserName.Equals(_sammyUserName) && uc.Client.PublicId.Equals(_sammyClientPublicIdConfidential)); Assert.IsNotNull(userClient); userClient.RefreshToken = jwtTokenDto.Token; context.Update(userClient); context.Commit(); } var formContent = BuildFormContent( _sammyClientPublicIdConfidential, String.Empty, OAuthConvention.GrantTypeRefreshToken, jwtTokenDto.Token, String.Empty, _sammyReturnUrlConfidential, _sammyScopeWording, _sammyUserName); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _client.DefaultRequestHeaders.Authorization = BuildAuthenticationHeaderValue(_sammyClientPublicIdConfidential, _sammyClientSecretConfidential); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/token"); request.Content = formContent; var httpResponseMessage = await _client.SendAsync(request); Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode); await CheckResponseContentIsValid(httpResponseMessage); }
public async Task <ActionResult <TokenOutput> > GetToken() { Guid organizationId = Guid.Parse(User.FindFirst("organizationId").Value); Organization organization = await OrganizationCollection.AsQueryable().FirstOrDefaultAsync(o => o.Id == organizationId); if (organization == null) { return(Forbid("Authenticated organization not found on the database")); } return(new TokenOutput(JwtService.GenerateToken(organization))); }
public ActionResult <string> SignIn(LoginViewModel login) { if (ValidateUser(login)) { return(jwt.GenerateToken(login.Username)); } else { return(BadRequest()); } }
public IActionResult Login([FromBody] LogInputModel model) { var user = _userService.Validate(model.UserName, model.Password); if (user == null) { return(BadRequest("Username or password is incorrect")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public IActionResult Login([FromBody] UserInputModel model) { var user = _userService.Validate(model.UserName, model.Password); if (user == null) { return(BadRequest("Acceso Denegado Usuario y/o contraseña incorrectos")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public IActionResult Login(LoginInputModel model) { var user = _userService.Validate(model.Username, model.Password); if (user == null) { return(BadRequest("Usuario o Contraseña esta mal escrita")); } var response = _jwtService.GenerateToken(user); return(Ok(response)); }
public void GenerateAsymmetricJwt_InstantiateServiceWithWrongKeySize_ShouldThrowException(int wrongKeySize) { Assert.ThrowsAny <Exception>(() => { using (var rsa = RSA.Create(wrongKeySize)) { var jwt = new JwtService(rsa.ExportParameters(true)); var token = jwt.GenerateToken(); Assert.True(string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token)); } }); }
public ActionResult <UsersViewModel> Login([FromBody] UsersInputModel model) { var user = _usersService.Validate(model.UserName, model.Password); if (user != null) { var response = _jwtService.GenerateToken(user); response.Estado = user.Estado; response.TipoUsuario = user.TipoUsuario; return(Ok(response)); } return(BadRequest("Usuario o clave es incorrecta")); }
public async Task GenerateToken_Expired_ShouldFailToValidate() { var jwt = new JwtService(key, clockSkew: TimeSpan.Zero); var token = jwt.GenerateToken(lifetime: TimeSpan.FromMilliseconds(250)); await Task.Delay(750); var result = jwt.ValidateToken(token); Assert.False(result.Successful); Assert.Null(result.ValidatedToken); Assert.NotNull(result.ErrorMessage); Assert.IsType <SecurityTokenExpiredException>(result.Exception); }
public void GenerateAsymmetricJwtCorrectly_ValidationShouldAlsoSucceed(int keySize) { using (var rsa = RSA.Create(keySize)) { var jwt = new JwtService(rsa.ExportParameters(true)); var validator = new JwtService(rsa.ExportParameters(false)); var token = jwt.GenerateToken(lifetime: TimeSpan.FromMinutes(10)); var result = validator.ValidateToken(token); Assert.True(result.Successful); Assert.NotNull(result.ValidatedToken); } }
public IHttpActionResult GenerateToken([FromUri] int expiresInMinutes) { if (expiresInMinutes == 0) { return(BadRequest("Expiration must be greater than 0.")); } var domain = Request?.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty) ?? "http://localhost:50602"; var jwt = new JwtService(domain); return(Ok(jwt.GenerateToken(expiresInMinutes))); }
public void GenerateToken_NotUsingUTCforNotBeforeParam_ShouldThrowArgumentExceptionWhenTryingToGenerateToken() { // Same as the test above, except DateTime.Now is used as notBefore argument inside GenerateToken(...). // Absolutely make ALWAYS sure that your 'notBefore' parameter is > DateTime.UtcNow! var jwt = new JwtService(key, clockSkew: TimeSpan.Zero); Assert.ThrowsAny <ArgumentException>(() => { var token = jwt.GenerateToken( lifetime: TimeSpan.FromSeconds(3), notBefore: new DateTime(int.MaxValue - 1, 10, 10, 10, 10, 10, DateTimeKind.Local) ); } ); }
public void GenerateToken_ValidateSingleClaim_ShouldSucceed(string type, string value) { var jwt = new JwtService(key, validateLifetime: false ); var claim = new Claim(type, value); var token = jwt.GenerateToken( claims: new[] { claim } ); var result = jwt.ValidateToken(token).Claims.ToArray()[0]; Assert.True(result.Type == claim.Type && result.Value == claim.Value && result.ValueType == claim.ValueType); }
public IActionResult Login([FromQuery] UsuarioLoginDto user) { try { var UserLogin = _queriesUser.VerificarUsuario(user.Login, user.Senha); if (UserLogin != null) { return(Ok(new { Token = JwtService.GenerateToken(UserLogin, _config), User = UserLogin })); } else { return(Ok("Usuario não existe")); } } catch (Exception ex) { return(Ok(ex)); } }
public IActionResult Login([FromBody] dynamic userRequest) { string username = userRequest.username; string password = userRequest.password; if (_dbContext.Users.Count(u => u.Username == username) != 1) { return(NotFound("用户名不存在")); } var user = _dbContext.Users.FirstOrDefault(u => u.Username == username && u.Password == password); return(user == null ? BadRequest("密码错误") : Success("登录成功", _jwt.GenerateToken(user.Id))); }
[HttpPost] //設定此Action只接受頁面POST資料傳入 public ActionResult Login(MembersLoginViewModel LoginMember) { //使用Service裡的方法來驗證登入的帳號密碼 string ValidateStr = membersService.LoginCheck(LoginMember.Account, LoginMember.Password); //判斷驗證後結果是否有錯誤訊息 if (String.IsNullOrEmpty(ValidateStr)) { //無錯誤訊息,則登入 //先清空Session HttpContext.Session.Clear(); //取得購物車保存 string Cart = cartService.GetCartSave(LoginMember.Account); //判斷是否有保存,若有則存入Session if (Cart != null) { HttpContext.Session["Cart"] = Cart; } //先藉由Service取得登入者角色資料 string RoleData = membersService.GetRole(LoginMember.Account); //設定JWT JwtService jwtService = new JwtService(); //從Web.Config撈出資料 //Cookie名稱 string cookieName = WebConfigurationManager.AppSettings["CookieName"].ToString(); string Token = jwtService.GenerateToken(LoginMember.Account, RoleData); ////產生一個Cookie HttpCookie cookie = new HttpCookie(cookieName); //設定單值 cookie.Value = Server.UrlEncode(Token); //寫到用戶端 Response.Cookies.Add(cookie); //設定Cookie期限 Response.Cookies[cookieName].Expires = DateTime.Now.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["ExpireMinutes"])); //重新導向頁面 return(RedirectToAction("Index", "Item")); } else { //有驗證錯誤訊息,加入頁面模型中 ModelState.AddModelError("", ValidateStr); //將資料回填至View中 return(View(LoginMember)); } }