private async Task <IActionResult> GetToken(TokenRequestVM model) { try { // check if there's an user with the given username DataCenterUser user = await UserManager.FindByNameAsync(model.vm_username); if (user == null || !await UserManager.CheckPasswordAsync(user, model.vm_password)) { // user does not exists or password mismatch return(new UnauthorizedResult()); } // username & password matches: create and return the Jwt token. DateTime now = DateTime.UtcNow; // Add the registered claims for JWT (RFC7519). // (For more info, see https://tools.ietf.org/html/rfc7519#section-4.1) var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUnixTimeSeconds().ToString()) }; var tokenExpirationMins = Configuration.GetValue <int>("Auth:Jwt:TokenExpirationInMinutes"); var issuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["Auth:Jwt:Key"])); var token = new JwtSecurityToken( issuer: Configuration["Auth:Jwt:Issuer"], audience: Configuration["Auth:Jwt:Audience"], claims: claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(tokenExpirationMins)), signingCredentials: new SigningCredentials( issuerSigningKey, SecurityAlgorithms.HmacSha256) ); var encodedToken = new JwtSecurityTokenHandler().WriteToken(token); // build & return the response var response = new TokenResponseVM() { vm_token = encodedToken, vm_expiration = tokenExpirationMins, vm_username = user.UserName, vm_isadmin = user.Roles.Contains(DataCenterIdentities.AdminRole) }; return(Json(response)); } catch (Exception) { return(new UnauthorizedResult()); } }
private bool HasRole(string role) { try { var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; DataCenterUser myUser = UserManager.FindByIdAsync(userId).Result; return(myUser.Roles.Contains(role)); } catch (Exception) { return(false); } }
/// <summary> /// Get a string that represents the currently logged on user (based on the ClaimsPrincipal) /// </summary> /// <returns></returns> private string GetUser() { try { var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; DataCenterUser myUser = UserManager.FindByIdAsync(userId).Result; return(myUser.UserName); } catch (Exception) { return("Guest"); } }
/// <summary> /// Get a string that contains a comma separated set of roles for the current user (based on the ClaimsPrincipal) /// </summary> /// <returns></returns> private string GetRoles() { try { var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; DataCenterUser myUser = UserManager.FindByIdAsync(userId).Result; string roles = String.Empty; foreach (string role in myUser.Roles) { roles = roles + role + ", "; } return(roles.Substring(0, roles.Length - 2)); } catch (Exception) { return("<none>"); } }