public string GenerateAuthenticationToken(string username) { // Get the user OboeteUser user = GetUser(username, true); // State the claims this token will have. var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.NameId, user.OboeteUserID.ToString()), new Claim(ClaimsIdentity.DefaultNameClaimType, username), new Claim("SecurityStamp", user.SecurityStamp.ToString()) }; // Specify the encoding var credentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config.SecretKey)), SecurityAlgorithms.HmacSha256 ); // Create the token object var token = new JwtSecurityToken( issuer: Config.Issuer, audience: Config.Audience, claims: claims, expires: DateTime.Now.AddHours(6), signingCredentials: credentials ); // Encrypt the token and return it as a string return(new JwtSecurityTokenHandler().WriteToken(token)); }
public bool CredentialsValid(string username, string password) { // Credentials cannot be null or empty, so we automatically know these are invalid without a database check if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { return(false); } OboeteUser user = GetUser(username); // Check a user with that username exists and password match if (user == null || !HashMatch(password, user.PasswordHash)) { return(false); } return(true); }
public string GenerateRememberMeToken(string username) { OboeteUser user = GetUser(username, true); // Generate the GUIDs var newToken = Guid.NewGuid().ToString(); var selector = Guid.NewGuid().ToString(); // State the claims this token will have. We store the selector, token and security stamp var claims = new Claim[] { new Claim("SecurityStamp", user.SecurityStamp.ToString()), new Claim("Selector", selector), new Claim("Token", newToken), new Claim(ClaimsIdentity.DefaultNameClaimType, username) }; // Specify the encoding var credentials = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config.SecretKey)), SecurityAlgorithms.HmacSha256 ); // Create the token object. The remember me token is valid for 12 months var token = new JwtSecurityToken( issuer: Config.Issuer, audience: Config.Audience, claims: claims, expires: DateTime.Now.AddMonths(12), signingCredentials: credentials ); //TODO: Write the token to the database var userTokenRecord = new OboeteUserLoginToken(user.OboeteUserID, HashString(newToken), DateTime.Now.AddMonths(12)); DbContext.OboeteUserLoginTokens.Add(userTokenRecord); DbContext.SaveChanges(); // Encrypt the token and return it as a string return(new JwtSecurityTokenHandler().WriteToken(token)); }