public async Task <UserInfo> Authenticate(AuthenticateInfo authorizeInfo) { if (string.IsNullOrEmpty(authorizeInfo.Login)) { throw new ValidationException(new List <ValidationFailure>() { new ValidationFailure("Login", "Can't be null or empty") }); } if (string.IsNullOrEmpty(authorizeInfo.Password)) { throw new ValidationException(new List <ValidationFailure>() { new ValidationFailure("Password", "Can't be null or empty") }); } var user = await _context.Users .Include(x => x.UserSettingInfo) .SingleOrDefaultAsync(x => x.UserSettingInfo.Login == authorizeInfo.Login); if (user != null && PasswordHelper.VerifyPasswordHash( authorizeInfo.Password, user.UserSettingInfo.PasswordHash, user.UserSettingInfo.PasswordSalt)) { return(user); } throw new UserNotFoundException($"The user was not found."); }
/// <summary> /// Call this to get the JWT token that will be used in other web methods /// </summary> public IActionResult Authenticate([FromBody] AuthenticateInfo model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Id, Username = user.Username, FirstName = user.Firstname, LastName = user.Lastname, Token = tokenString })); }
public void ValidationTest_Valid() { AuthenticateInfo info = new AuthenticateInfo() { Password = "******", RepeatPassword = "******" }; info.Validate(); Assert.IsFalse(info.HasErrors); Assert.IsFalse(info.GetErrors().Any()); }
public async void GenerateClaimsForIdentity_NoIssuer_ThrowException() { var expectedInvalidIssuer = TestHelper.GenerateRandomString(); var issuer = TestHelper.GenerateRandomString(); authenticateInfo = GenerateAuthenticateInfo(issuer, false); authenticateInfo.Properties.Items["scheme"] = FabricIdentityConstants.AuthenticationSchemes.Azure; AppConfiguration.AzureActiveDirectorySettings.IssuerWhiteList = new string[] { issuer = expectedInvalidIssuer }; Exception expectedException = null; try { var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.True(false, "The code should not call this line. It should have thrown an exception."); } catch (Exception exc) { expectedException = exc; } Assert.NotNull(expectedException); Assert.IsType <MissingIssuerClaimException>(expectedException); Assert.Equal <string>( ExceptionMessageResources.MissingIssuerClaimMessage, expectedException.Message); }
public void ValidationTest_PropertyNull() { AuthenticateInfo info = new AuthenticateInfo(); info.Validate(); Assert.IsFalse(info.HasErrors); Assert.IsFalse(info.GetErrors().Any()); }
public void ValidationTest_InValid() { AuthenticateInfo info = new AuthenticateInfo() { Password = "******", RepeatPassword = "******" }; info.Validate(); Assert.IsTrue(info.HasErrors); Assert.AreEqual(AuthenticateInfo.RepeatPasswordErrorMessage, info.GetErrors().Single().ErrorMessage); Assert.AreEqual(AuthenticateInfo.RepeatPasswordErrorMessage, info.GetErrors("RepeatPassword").Single().ErrorMessage); }
private async Task <string> GetToken() { AuthenticateInfo info = await HttpContext.Authentication.GetAuthenticateInfoAsync(JwtBearerDefaults.AuthenticationScheme); var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); return(tokenHandler.ReadToken(info.Properties.Items[".Token.access_token"]).ToString()); }
public async void GenerateClaimsForIdentity_HappyPathNonAzure_RemovesNameIdentitiferUserIdClaim() { authenticateInfo = GenerateAuthenticateInfo(null, true, false); var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.False(result.Claims.Any(x => x.Type == ClaimTypes.NameIdentifier)); }
private static List <Claim> GetClaims(AuthenticateInfo externalLogin) { var tempUser = externalLogin?.Principal; if (tempUser == null) { throw new Exception("External authentication error"); } return(tempUser.Claims.ToList()); }
private async Task <ClaimsResult> GenerateNewClaimsResult(AuthenticateInfo info, AuthorizationRequest context) { // provider and scheme look the same, but if you see the values // FabricIdentityConstants.AuthenticationSchemes.Azure = "AzureActiveDirectory" // you will notice there are 2 different values, one for the provider and the other for the scheme var provider = info.Properties.Items["scheme"]; var schemeItem = info.Properties.Items.FirstOrDefault(i => i.Key == "scheme").Value; var claimsPrincipal = info?.Principal; if (claimsPrincipal == null) { throw new Exception("External authentication error"); } var claims = claimsPrincipal.Claims.ToList(); var userIdClaim = this.GetUserIdClaim(claims); var subjectId = AzureADSubjectId(claims); if (!string.IsNullOrEmpty(subjectId)) { var externalUser = await _externalIdentityProviderService.FindUserBySubjectId(subjectId); if (externalUser != null) { if (externalUser.FirstName != null) { claims.Add(new Claim(JwtClaimTypes.GivenName, externalUser.FirstName)); } if (externalUser.LastName != null) { claims.Add(new Claim(JwtClaimTypes.FamilyName, externalUser.LastName)); } if (externalUser.Email != null) { claims.Add(new Claim(JwtClaimTypes.Email, externalUser.Email)); } } } return(new ClaimsResult { ClientId = context?.ClientId, UserId = userIdClaim.Value, Provider = provider, SchemeItem = schemeItem, Claims = claims, UserIdClaim = userIdClaim }); }
public async void GenerateClaimsForIdentity_HappyPathAzure_ReturnsClaimsResult() { var issuer = TestHelper.GenerateRandomString(); authenticateInfo = GenerateAuthenticateInfo(issuer); authenticateInfo.Properties.Items["scheme"] = FabricIdentityConstants.AuthenticationSchemes.Azure; AppConfiguration.AzureActiveDirectorySettings.IssuerWhiteList = new string[] { issuer = "LOCAL AUTHORITY" }; var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); AssertClaimsResult(authenticateInfo, authorizationRequest, result); }
public async Task <User> getUserAsync() { AuthenticateInfo authInfo = await _ctxAccessor.HttpContext.Authentication.GetAuthenticateInfoAsync("CookieMiddlewareInstance"); if (authInfo.Principal == null || !authInfo.Principal.Identity.IsAuthenticated) { return(null); } //string fname = authInfo.Principal.FindFirst("fname").Value; //string lname = authInfo.Principal.FindFirst("lname").Value; string email = authInfo.Principal.FindFirst("email").Value; //return new User() { fname = fname, lname = lname, email = email }; return(_db.Users.FirstOrDefault(u => u.email == email)); }
private AuthenticationProperties GenerateAuthenticationProperties(AuthenticateInfo info) { //if the external provider issued an id_token, we'll keep it for signout AuthenticationProperties props = null; var id_token = info.Properties.GetTokenValue("id_token"); if (id_token != null) { props = new AuthenticationProperties(); props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } return(props); }
private async Task <IActionResult> IssueCookieAndRedirectAsync( UserAccount userAccount, string provider, string returnUrl, AuthenticateInfo info, List <Claim> claims) { var additionalClaims = new List <Claim>(); // if the external system sent a session id claim, copy it over var sid = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { additionalClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout AuthenticationProperties props = null; var id_token = info.Properties.GetTokenValue("id_token"); if (id_token != null) { props = new AuthenticationProperties(); props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } // issue authentication cookie for user await HttpContext.Authentication.SignInAsync( userAccount.Id.ToString(), userAccount.Email, provider, props, additionalClaims.ToArray()); // delete temporary cookie used during external authentication await HttpContext.Authentication.SignOutAsync( IdentityServerConstants.ExternalCookieAuthenticationScheme); // validate return URL and redirect back to authorization endpoint if (_interaction.IsValidReturnUrl(returnUrl)) { return(Redirect(returnUrl)); } return(Redirect("~/")); }
private void AssertClaimsResult(AuthenticateInfo info, AuthorizationRequest context, ClaimsResult result) { Assert.Equal <string>(context.ClientId, result.ClientId); Assert.Equal <string>(info.Properties.Items["scheme"], result.Provider); Assert.Equal <string>(info.Properties.Items.FirstOrDefault(i => i.Key == "scheme").Value, result.SchemeItem); var expectedUserId = info?.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject); Assert.Equal <string>(expectedUserId.Value, result.UserId); Assert.Equal <Claim>(expectedUserId, result.UserIdClaim); var expectedClaims = info?.Principal.Claims.ToArray(); // we remove one because user Id claim should be removed Assert.Equal <int>(expectedClaims.Length - 1, result.Claims.Count); AssertAdditionalClaims(info?.Principal.Claims, result); AssertAuthenticationProperties(info, result); }
public async void GenerateClaimsForIdentity_NoUserIdClaim_ThrowException() { authenticateInfo = GenerateAuthenticateInfo(null, true, false, false); Exception expectedException = null; try { var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.True(false, "The code should not call this line. It should have thrown an exception."); } catch (Exception exc) { expectedException = exc; } Assert.NotNull(expectedException); Assert.IsType <MissingUserClaimException>(expectedException); Assert.Equal <string>( ExceptionMessageResources.MissingUserClaimMessage, expectedException.Message); }
/// <summary> /// Generates all information needed to create an access token for a given user. /// </summary> /// <param name="info">Authentication information</param> /// <param name="context">Authorization Request</param> /// <returns>Returns all the information into an object call ClaimsResult</returns> public async Task <ClaimsResult> GenerateClaimsForIdentity(AuthenticateInfo info, AuthorizationRequest context) { CheckWhetherArgumentIsNull(info, nameof(info)); // NOTE: context may be null. because of this, we are not going to // validate context var result = await GenerateNewClaimsResult(info, context); if (this.IsExternalTokenAzureAD(result.SchemeItem)) { this.ValidateAzureADExternalToken(result); } //remove the user id claim from the claims collection and move to the userId property //also set the name of the external authentication provider result.Claims.Remove(result.UserIdClaim); //get the client id from the auth context result.AdditionalClaims = this.GenerateAdditionalClaims(result); result.AuthenticationProperties = this.GenerateAuthenticationProperties(info); return(result); }
public async Task <IActionResult> About() { AuthenticateInfo info = await Request.HttpContext.Authentication.GetAuthenticateInfoAsync(CookieAuthenticationDefaults.AuthenticationScheme); string CookieResult = info.Principal.Claims.First().Value; byte[] sessionUserNameBytes; string sessionUserName = string.Empty; if (HttpContext.Session.TryGetValue("MySessionName", out sessionUserNameBytes)) { sessionUserName = System.Text.Encoding.UTF8.GetString(sessionUserNameBytes); } ViewBag.SessionUserName = sessionUserName; ViewBag.CookieUserName = CookieResult; ViewBag.Blog = JsonConvert.DeserializeObject <Blog>(HttpContext.Session.GetString("MyBlog")); ViewData["Message"] = "Your application description page."; return(View()); }
public YggdrasilAuthenticate(YggdrasilResponse status, AuthenticateInfo info) { Status = status; Info = info; }
internal static async Task ReIssueSignInCookie(this HttpContext context, AuthenticateInfo info) { var options = context.RequestServices.GetRequiredService <IdentityServerOptions>(); await context.Authentication.SignInAsync(options.AuthenticationOptions.EffectiveAuthenticationScheme, info.Principal, info.Properties); }
private static string GetScheme(AuthenticateInfo externalLogin) { return(externalLogin.Properties.Items["scheme"]); }
private void AssertAuthenticationProperties(AuthenticateInfo info, ClaimsResult result) { Assert.Equal <string>(info.Properties.GetTokenValue("id_token"), result.AuthenticationProperties.GetTokenValue("id_token")); }
private async Task <string> GetEncodedToken() { AuthenticateInfo info = await HttpContext.Authentication.GetAuthenticateInfoAsync(JwtBearerDefaults.AuthenticationScheme); return(info.Properties.Items[".Token.access_token"]); }
public GenerateClaimsForIdentityTests() : base() { authenticateInfo = GenerateAuthenticateInfo(); authorizationRequest = GenerateAuthorizationRequest(); }