public async Task <IActionResult> Login(LoginModel model) { if (ModelState.IsValid) { Users user = UsersCrud.Login(model.Email, model.Password); if (user != null) { //await Authenticate(user); // аутентификация ClaimsIdentity identity = GetIdentity(model.Email, model.Password); var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.AddMinutes(1), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); HttpContext.Response.Cookies.Append(AuthOptions.CookiesName, encodedJwt.ToString(), new CookieOptions { MaxAge = TimeSpan.FromMinutes(1) }); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "Некорректные логин и(или) пароль"); } return(View(model)); }
public string CreateToken(User user) { // Create claims for the payload body var claimsData = new List <Claim>(); claimsData.Add(new Claim("Email", user.Email)); claimsData.Add(new Claim("FullName", user.FullName)); // The recommended way is to store your secrets in some file that is not accessible by anyone. // For more information, look up secrets.json in .Net Core projects. string secret = "your_secret_here"; // Create key var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); var signInCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); // Create token var token = new JwtSecurityToken( issuer: "localhost", expires: DateTime.Now.AddYears(1), claims: claimsData, signingCredentials: signInCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(tokenString.ToString()); }
public string generatToken(string userName) { int ExpiringHours = 240; var claim = new[] { new Claim("User", userName), new Claim("Expires", DateTime.Now.AddHours(ExpiringHours).ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["Secret"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken( null, null, claim, expires: DateTime.Now.AddHours(ExpiringHours), signingCredentials: credentials ); string token = new JwtSecurityTokenHandler().WriteToken(jwtToken); bool saveCookie = SaveToCookie("TokenValue", token); Account account = context.Accounts.FirstOrDefault(a => a.UserName == userName); account.Token = token; context.SaveChanges(); return(token.ToString()); }
public async Task <string> Login(LoginModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { var userRoles = await _userManager.GetRolesAsync(user); var authClaims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (var userRole in userRoles) { authClaims.Add(new Claim(ClaimTypes.Role, userRole)); } var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); var t = new JwtSecurityTokenHandler().WriteToken(token); return(t.ToString()); } return(null); }
public IActionResult Unwind(string token) { var tokenx = new JwtSecurityTokenHandler().ReadJwtToken(token); //NO Signature validation here yet. return(Ok(tokenx.ToString())); }
public async Task <IActionResult> Login(UserVM userVM) { if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(userVM.Username, userVM.Password, false, false); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(userVM.Username); using (var connection = new SqlConnection(_configuration.GetConnectionString("MyNetCoreConnection"))) { var procName = "SP_GetRole"; parameters.Add("@ID", user.Id); IEnumerable <UserVM> data = connection.Query <UserVM>(procName, parameters, commandType: CommandType.StoredProcedure); foreach (UserVM users in data) { userVM.Role = users.Role; } } if (user != null) { var claims = new List <Claim> { //new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]), //new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()) new Claim("Username", user.UserName), new Claim("Email", user.Email), new Claim("Role", userVM.Role) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddMinutes(10), signingCredentials: signIn ); var idtoken = new JwtSecurityTokenHandler().WriteToken(token); claims.Add(new Claim("TokenSecurity", idtoken.ToString())); return(Ok(idtoken)); } } return(BadRequest(new { message = "Username or Password is Invalid" })); } else { return(BadRequest("Failed")); } }
public virtual KeyValuePair<string, string> WriteToken(IEnumerable<Claim> claims, string issuer, string audience, DateTime expires) { var securityKey = GetSymmetricKey(); var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey)); var credentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, expires: expires, signingCredentials: credentials ); var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); var keyObject = new KeyValuePair<string, string>(securityKey, jwtToken.ToString()); return keyObject; }
internal static string getToken(IConfiguration configuration) { var now = DateTime.UtcNow; var secret = configuration.GetValue <string>("Audience:Secret"); var iss = configuration.GetValue <string>("Audience:Iss"); var aud = configuration.GetValue <string>("Audience:Aud"); var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, "ClientAPI"), new Claim(JwtRegisteredClaimNames.Sub, "ClientAPI"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64) }; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = iss, ValidateAudience = true, ValidAudience = aud, ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true, }; var jwt = new JwtSecurityToken( issuer: iss, audience: aud, claims: claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(30)), signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var responseJson = new { access_token = encodedJwt, expires_in = (int)TimeSpan.FromMinutes(30).TotalSeconds }; return(encodedJwt.ToString()); }
public IActionResult Get(string name, string password) { //just hard code here if (name == "cp" && password == "123") { var now = DateTime.UtcNow; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, name), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer), }; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("this is the secret to add some default jwt token lets see how it works")); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = "chandra", ValidateAudience = true, ValidAudience = "enduser", ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true, }; var jwt = new JwtSecurityToken( issuer: "chandra", audience: "enduser", claims: claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(2)), signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var result = new { access_token = encodedJwt.ToString(), expires_in = TimeSpan.FromMinutes(2000).TotalSeconds.ToString() }; return(Ok(result)); } return(NotFound()); }
public async Task <IActionResult> Get(UserVM userVM) { if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(userVM.Username, userVM.Password, false, false); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(userVM.Username); if (user != null) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddMinutes(10), signingCredentials: signIn ); var idtoken = new JwtSecurityTokenHandler().WriteToken(token); claims.Add(new Claim("TokenSecurity", idtoken.ToString())); return(Ok(idtoken + "..." + user.Email + "..." + user.Id)); } } return(BadRequest(new { message = "Username or Password is Invalid" })); } else { return(BadRequest("Failed")); } }
public async Task <string> Secret() { var accessToken = await HttpContext.GetTokenAsync("access_token"); var idToken = await HttpContext.GetTokenAsync("id_token"); var refreshToken = await HttpContext.GetTokenAsync("refresh_token"); // This will have the information about claims var claims = User.Claims.ToList(); var _access_token = new JwtSecurityTokenHandler().ReadJwtToken(accessToken); // id_token is primarily about our authentication state, e.g. user id is // authentication information, rather than personal user information such as email. // It's used to identify who is authenticated and how they are authenticated. var _id_token = new JwtSecurityTokenHandler().ReadJwtToken(idToken); var result = await GetSecret(accessToken); return("access_token:\n" + _access_token.ToString() + "\nid_token\n" + _id_token.ToString()); }
public async Task <LoginResultDto> Login(string userName, string password) { var findByEmail = await _userManager.FindByEmailAsync(userName); if (findByEmail != null) { var result = await _userManager.CheckPasswordAsync(findByEmail, password); if (result) { List <Claim> myClaims = new List <Claim>(); myClaims.Add(new Claim("Role", "UserModel")); var roles = new JwtSecurityToken(claims: myClaims); var token = new JwtSecurityTokenHandler().WriteToken(roles); return(new LoginResultDto { Token = token.ToString() }); } return(null); } return(null); }
public IActionResult Get(string EmailID, string password) { UserDetailsWithSecureToken objSecureToken = new UserDetailsWithSecureToken(); var userDetail = _context.CurrentUsers.FromSql <CurrentUserDetails>("spCheckUserDetailsById {0}", EmailID).ToList().FirstOrDefault(); //if(userDetail.EmailID == EmailID) //{ // userDetail.EmailID = "true"; //} //just hard code here. string EncodePass = EncodePassword(password); string DecodedPass = DecodePassword(EncodePass); if (userDetail.EmailID == EmailID && userDetail.ProfilePassword == DecodedPass) //if (userDetail.EmailID == EmailID && userDetail.ProfilePassword == password) { var now = DateTime.UtcNow; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, EmailID), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64) }; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("this is the secret key to add some default jwt token, lets see how it works")); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = "EmpPortalIssuer", ValidateAudience = true, ValidAudience = "EmpPortalAudience", ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true, }; var jwt = new JwtSecurityToken( issuer: "EmpPortalIssuer", audience: "EmpPortalAudience", claims: claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(20)), signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var responseJson = new { access_token = encodedJwt //expires_in = (int)TimeSpan.FromMinutes(8000).TotalSeconds }; objSecureToken.EmailID = userDetail.EmailID; objSecureToken.EmployeeID = userDetail.EmployeeID; objSecureToken.EmployeeName = userDetail.EmployeeName; objSecureToken.UserID = userDetail.UserID; objSecureToken.UserRole = userDetail.UserRole; objSecureToken.ProfilePassword = userDetail.ProfilePassword; objSecureToken.SecureToken = encodedJwt.ToString(); return(Ok(objSecureToken)); } else { return(Ok("")); } }
async Task <IActionResult> loginDetails(UserVM model) { try { string email = "", userId = "", firstName = "", lastName = ""; Result result = await _auth.Login(model); if (result != null) { if (result.IsSuccess && result.Data != null) { UserVM userData = (UserVM)result.Data; email = ((UserVM)result.Data).Email; userId = ((UserVM)result.Data).UserId.ToString(); firstName = ((UserVM)result.Data).FirstName; lastName = ((UserVM)result.Data).LastName; var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim("USERID", !string.IsNullOrEmpty(userId) ? userId : ""), new Claim("EMAIL", !string.IsNullOrEmpty(email) ? email : "") }; string tokenValue = _config.GetSection("AppSettings:Token").Value; byte[] tokenByte = Encoding.UTF8.GetBytes(tokenValue); var key = new SymmetricSecurityKey(tokenByte); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var JWToken = new JwtSecurityToken( issuer: "https://localhost:44319/", audience: "https://localhost:44319/", claims: GetUserClaims(userData), notBefore: new DateTimeOffset(DateTime.Now).DateTime, expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime, signingCredentials: creds ); var tokenHandler = new JwtSecurityTokenHandler(); var token = new JwtSecurityTokenHandler().WriteToken(JWToken); HttpContext.Session.SetString("JWToken", token.ToString()); return(Ok(new { Message = "Login Successful", token = token, statusCode = StatusCode(201), userId = userId, firstName = firstName, lastName = lastName, email = email != null ? email : "", })); } else { return(Unauthorized("Invalid username or password")); } } else { return(Unauthorized("Invalid username or password")); } } catch (Exception ex) { ex.Message.ToString(); return(BadRequest()); } }
public async Task <IActionResult> Token(LoginModel model) { if (model == null || string.IsNullOrWhiteSpace(model.Email) || string.IsNullOrWhiteSpace(model.Password)) { return(BadRequest()); } var user = _userManager.Users.FirstOrDefault(u => u.Email == model.Email); var valid = await _userManager.CheckPasswordAsync(user, model.Password); //this would make sure the user confirmed their email address, but we don't have a dummy email we can use if (user.EmailConfirmed) { if (valid) { var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Email, user.Email)); //claims.Add(new Claim(ClaimTypes.GivenName, user.name)); 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 response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds, is_admin = user.Admin, }; var json = JsonConvert.SerializeObject(response, _serializerSettings); //return new OkObjectResult(json); //use above for phone api Token token = new Token(); token.TokenString = encodedJwt.ToString(); HttpContext.Session.SetJson("Token", token); return(RedirectToAction("Index", "Home")); } else { if (user != null) { user.AccessFailedCount += 1; } return(Unauthorized()); } } else { return(Ok("Make sure you confirm your email address")); } }