public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await _userMgr.FindByNameAsync(model.UserName); if (user != null) { if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { var userClaims = await _userMgr.GetClaimsAsync(user); // create claims that will be passed to a token var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName), new Claim(JwtRegisteredClaimNames.Email, user.Email) }.Union(userClaims); // Create signing credentials //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYLONGKEYVALUETHATISSECURE")); //var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // create token var token = new JwtSecurityToken( //issuer: "http://mycodecamp.org", //audience: "http://mycodecamp.org", //claims: claims, //expires: DateTime.UtcNow.AddMinutes(15), //signingCredentials: creds issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(15), signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } } catch (Exception ex) { _logger.LogError($"+++++++++Exception thrown while creating JWT++++++++++++++++++++++ {ex}"); } return(BadRequest("Failed to generate token")); }
public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await userManager.FindByNameAsync(model.UserName); if (user != null) { if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { var userClaims = await userManager.GetClaimsAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName), new Claim(JwtRegisteredClaimNames.Email, user.Email), }.Union(userClaims); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: tokenSettings.Issuer, audience: tokenSettings.Audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(15), signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } } catch (Exception exception) { logger.LogError("Threw exception while creating JWT", exception); } return(BadRequest("Failed to generate token")); }
public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { //verifies if the provided password is the same as the one in the database. if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { var userClaims = await _userManager.GetClaimsAsync(user); //claims from identity system eg.roles var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), //Jti is data that ensures uniqueness i.e. guid new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName), new Claim(JwtRegisteredClaimNames.Email, user.Email) }.Union(userClaims); // use Union to combine two arrays //The string should be stored in config var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(20), signingCredentials: creds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } } catch (Exception ex) { _logger.LogError($"Exception thrown while creating JWT - {ex}"); } return(BadRequest("Could not create the token")); }
public async Task <IActionResult> Login([FromBody] CredentialModel model) { try { var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false); if (result.Succeeded) { return(Ok("Login succeded")); } } catch (Exception ex) { _logger.LogError($"Exception thrown while logging {ex}"); } return(BadRequest("Failed to login")); }
public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await _userMgr.FindByNameAsync(model.UserName); if (user != null) { var result = await _signInMgr.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; // в боевом коде нужно брать из секретного хранилища или конфига var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(60), signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, })); } } } catch (Exception e) { _logger.LogError($"Exception thrown while creating JWT: {e}"); } return(BadRequest("Failed to generate token")); }
public async Task <IActionResult> Login([FromBody] CredentialModel model) { try { var result = await signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false); if (result.Succeeded) { return(Ok()); } } catch (Exception exception) { logger.LogError("Threw exception while logging in", exception); } return(BadRequest("Failed to login")); }
public async Task<IActionResult> Login([FromBody] CredentialModel model) { try { // isPersisted = false => it is not stored in the browser after the browser is closed // lockoutOnFailure => not lockout the user after this unsuccessful attempt to login var result = await signInMgr.PasswordSignInAsync(model.UserName, model.Password, false, false); if (result.Succeeded) { return Ok(); } } catch(Exception ex) { logger.LogError($"Exception was thrown wile authenticating - {ex}"); } return BadRequest("Failed to login."); }
[EnableCors("Wildermuth")] //Used with cookie authentication public async Task <IActionResult> Login([FromBody] CredentialModel model) { try { var result = await _signInMgr.PasswordSignInAsync(model.UserName, model.Password, false, false); // first false means cookie isn't persisted after browse is closed if (result.Succeeded) { return(Ok()); } } catch (Exception ex) { _logger.LogError($"Exception thrown while logging in: {ex}"); } return(BadRequest("Failed to login")); }
public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await _userManager.FindByNameAsync(model.Username); if (user != null) { if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { var userClaims = await _userManager.GetClaimsAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }.Union(userClaims); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512); var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], expires: DateTime.UtcNow.AddMinutes(15), claims: claims, signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } } catch (Exception ex) { _logger.LogError($"Exception thrown while creating the token : {ex}"); } return(BadRequest("Failed to created the token")); }
public async Task <IActionResult> CreateToken([FromBody] CredentialModel model) { try { var user = await _userMgr.FindByNameAsync(model.UserName); if (user != null) { var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var userClaims = await _userMgr.GetClaimsAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, model.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName), new Claim(JwtRegisteredClaimNames.Email, user.Email) }.Union(userClaims);; var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], expires: DateTime.Now.AddHours(1), claims: claims, signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, message = "Success!!" })); } } catch (Exception exp) { _logger.LogError($"Exception throwing when creating JWT {exp}"); } return(BadRequest("Failed to generate token")); }
public async Task <IActionResult> Post([FromBody] CredentialModel model) { // Validate the Credential var user = await _userManager.FindByEmailAsync(model.Username); if (user != null) { if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { // Claims var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName), new Claim("FavoriteColor", "Blue") }; // Keys var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var signingCreds = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); // Build the Token var token = new JwtSecurityToken( issuer: _config["Tokens:Issuer"], audience: _config["Tokens:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(10), signingCredentials: signingCreds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } } return(BadRequest()); }