/// <summary> /// Gets the refresh token. /// </summary> /// <param name="refreshTokenHandle">The refresh token handle.</param> /// <returns></returns> public async Task <RefreshToken> GetRefreshTokenAsync(string refreshTokenHandle) { using var activity = Tracing.StoreActivitySource.StartActivity("DefaultRefreshTokenStore.GetRefreshToken"); var refreshToken = await GetItemAsync(refreshTokenHandle); if (refreshToken != null && refreshToken.Version < 5) { #pragma warning disable CS0618 // Type or member is obsolete var user = new IdentityServerUser(refreshToken.AccessToken.SubjectId); if (refreshToken.AccessToken.Claims != null) { foreach (var claim in refreshToken.AccessToken.Claims) { user.AdditionalClaims.Add(claim); } } refreshToken.Subject = user.CreatePrincipal(); refreshToken.ClientId = refreshToken.AccessToken.ClientId; refreshToken.Description = refreshToken.AccessToken.Description; refreshToken.AuthorizedScopes = refreshToken.AccessToken.Scopes; refreshToken.SetAccessToken(refreshToken.AccessToken); refreshToken.AccessToken = null; refreshToken.Version = 5; #pragma warning restore CS0618 // Type or member is obsolete } return(refreshToken); }
public async Task <string> RefreshToken(IdentityUser <int> user) { var identityPricipal = await _principalFactory.CreateAsync(user); var identityUser = new IdentityServerUser(user.Id.ToString()) { AdditionalClaims = identityPricipal.Claims.ToArray(), DisplayName = user.UserName, AuthenticationTime = DateTime.UtcNow, IdentityProvider = IdentityServerConstants.LocalIdentityProvider }; var request = new TokenCreationRequest(); request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new ValidatedRequest(); request.ValidatedRequest.Subject = request.Subject; request.ValidatedRequest.SetClient(Config.Clients().First()); request.Resources = new Resources(Config.IdentityResources(), new List <ApiResource>()); request.ValidatedRequest.Options = _options; request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims; var token = await _tokenService.CreateAccessTokenAsync(request); token.Issuer = "..."; return(await _refreshTokenService.CreateRefreshTokenAsync(identityPricipal, token, Config.Clients().First())); }
private async Task <string> GenrateToken(ITokenService TS, IUserClaimsPrincipalFactory <ApplicationUser> principalFactory, IdentityServerOptions options, ApplicationUser user) { var Request = new TokenCreationRequest(); var User = await _userManager.FindByIdAsync(user.Id); var IdentityPricipal = await principalFactory.CreateAsync(User); var IdentityUser = new IdentityServerUser(User.Id.ToString()); IdentityUser.AdditionalClaims = IdentityPricipal.Claims.ToArray(); IdentityUser.DisplayName = User.UserName; IdentityUser.AuthenticationTime = System.DateTime.UtcNow; IdentityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider; Request.Subject = IdentityUser.CreatePrincipal(); Request.IncludeAllIdentityClaims = true; Request.ValidatedRequest = new ValidatedRequest(); Request.ValidatedRequest.Subject = Request.Subject; Request.ValidatedRequest.SetClient(Config.Clients.First()); Request.ValidatedResources = new ResourceValidationResult(new Resources(Config.IdentityResources, new ApiResource[] { }, Config.ApiScopes)); Request.ValidatedRequest.Options = options; Request.ValidatedRequest.ClientClaims = IdentityUser.AdditionalClaims; var Token = await TS.CreateAccessTokenAsync(Request); Token.Issuer = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value; var TokenValue = await TS.CreateSecurityTokenAsync(Token); return(TokenValue); }
/// <summary> /// Processes the interaction logic. /// </summary> /// <param name="request">The request.</param> /// <param name="consent">The consent.</param> /// <returns></returns> public virtual async Task <InteractionResponse> ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) { Logger.LogTrace("ProcessInteractionAsync"); if (consent != null && consent.Granted == false && request.Subject.IsAuthenticated() == false) { // special case when anonymous user has issued a deny prior to authenticating Logger.LogInformation("Error: User denied consent"); return(new InteractionResponse { Error = OidcConstants.AuthorizeErrors.AccessDenied }); } var identityServerUser = new IdentityServerUser(request.ClientId) { DisplayName = request.Client.ClientName, AdditionalClaims = request.ClientClaims, AuthenticationTime = new DateTime?(DateTime.UtcNow) }; request.Subject = identityServerUser.CreatePrincipal(); var authenticationProperties = new AuthenticationProperties { IsPersistent = true, IssuedUtc = DateTime.UtcNow }; await _httpContextAccessor.HttpContext.SignInAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme, request.Subject, authenticationProperties); var result = new InteractionResponse(); return(result); }
public async Task <IActionResult> Login(LoginViewModel model) { var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); if (ModelState.IsValid) { if (_userStore.ValidateCredentials(model.Email, model.Password)) { var user = _userStore.FindByUsername(model.Email); var identityUser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username, AdditionalClaims = user.Claims }; await HttpContext.SignInAsync(identityUser.CreatePrincipal()); await _eventService.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); if (context != null) { return(Redirect(model.ReturnUrl)); } } } ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View(model)); }
public async Task <string> GetToken(string subjectId, string deviceId, string secret) { var request = new TokenCreationRequest(); var identityUser = new IdentityServerUser(subjectId); identityUser.DisplayName = deviceId; identityUser.AuthenticationTime = System.DateTime.UtcNow; identityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider; request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new ValidatedRequest(); request.ValidatedRequest.Subject = request.Subject; request.ValidatedRequest.SetClient(new Client() { ClientId = deviceId, AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret(secret.Sha256()) } }); request.Resources = new Resources(IdentityServerConfig.GetIdentityResources(), IdentityServerConfig.GetApiResources()); request.ValidatedRequest.Options = _options; request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims; var token = await _tokenService.CreateAccessTokenAsync(request); var tokenValue = await _tokenService.CreateSecurityTokenAsync(token); return(tokenValue); }
/// <summary> /// Initializes a new instance of the <see cref="ClaimsPrincipal"/> class with Claims from the Membership User /// </summary> /// <param name="user">Membership User</param> /// <param name="identityProvider">Identity Provider Name</param> /// <param name="claims">List of additional claims</param> /// <returns>Claims Principal</returns> public static ClaimsPrincipal Create(this MembershipUser user, string identityProvider, params Claim[] claims) { var identityServerUser = new IdentityServerUser(user.GetSubjectId()) { DisplayName = user.UserName, IdentityProvider = identityProvider, AdditionalClaims = claims }; return(identityServerUser.CreatePrincipal()); }
public static ClaimsPrincipal ToPrincipal(this UserDto user) { var identityServerUser = new IdentityServerUser(user.Id.ToString()) { DisplayName = user.UserName, AuthenticationTime = DateTimeOffset.UtcNow.UtcDateTime, AdditionalClaims = GetUserClaims(user).ToHashSet() }; return(identityServerUser.CreatePrincipal()); }
public async Task consent_page_should_have_authorization_params(Type storeType) { if (storeType != null) { _mockPipeline.OnPostConfigureServices += services => { services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType); }; _mockPipeline.Initialize(); } var user = new IdentityServerUser("bob") { Tenant = "tenant_value" }; await _mockPipeline.LoginAsync(user.CreatePrincipal()); var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token token", scope: "openid api1 api2", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce", acrValues: "acr_1 acr_2 tenant:tenant_value", extra: new { display = "popup", // must use a valid value form the spec for display ui_locales = "ui_locale_value", custom_foo = "foo_value" } ); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ConsentRequest.Should().NotBeNull(); _mockPipeline.ConsentRequest.Client.ClientId.Should().Be("client2"); _mockPipeline.ConsentRequest.DisplayMode.Should().Be("popup"); _mockPipeline.ConsentRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.ConsentRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.ConsentRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.ConsentRequest.Parameters.AllKeys.Should().Contain("custom_foo"); _mockPipeline.ConsentRequest.Parameters["custom_foo"].Should().Be("foo_value"); _mockPipeline.ConsentRequest.ValidatedResources.RawScopeValues.Should().BeEquivalentTo(new string[] { "api2", "openid", "api1" }); }
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { var container = storage.CreateCloudBlobClient().GetContainerReference("identity"); var local = container.GetBlockBlobReference("local.json"); if (await container.ExistsAsync() && await local.ExistsAsync()) { var localuser = JToken.Parse(local.DownloadTextAsync().GetAwaiter().GetResult()).ToObject <LocalUsersProvisionModel>(); logger.LogInformation("Testing {@localuser} agaisnt {@context} ", localuser, context); if (context.Password.Sha256() == localuser.Password && context.UserName == localuser.Email) { var svr = new IdentityServerUser(localuser.Email) { AuthenticationTime = systemClock.UtcNow.DateTime, AdditionalClaims = new[] { new Claim(JwtClaimTypes.GivenName, localuser.FirstName), new Claim(JwtClaimTypes.FamilyName, localuser.LastName), new Claim(JwtClaimTypes.Name, $"{localuser.FirstName} {localuser.LastName}") }, IdentityProvider = "local" }; var claimsPrincipal = svr.CreatePrincipal(); context.Result = new GrantValidationResult { Subject = claimsPrincipal }; return; } //idsrvBuilder.AddTestUsers(new List<IdentityServer4.Test.TestUser>{ new IdentityServer4.Test.TestUser{ // IsActive = true, Password = localuser.Password, SubjectId = localuser.Email, Username =localuser.Email, Claims=new []{ // new Claim(IdentityModel.JwtClaimTypes.GivenName ,localuser.FirstName), // new Claim(IdentityModel.JwtClaimTypes.FamilyName ,localuser.LastName), // new Claim(IdentityModel.JwtClaimTypes.Name ,$"{localuser.FirstName} {localuser.LastName}") // } // } }); } context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "local user not found"); }
// Based on https://stackoverflow.com/a/44322425/1249506 public async Task <IdentityServerToken> GetIdentityServerTokenForUserAsync(User user) { var request = new TokenCreationRequest(); var identityPricipal = await PrincipalFactory.CreateAsync(user); var identityUser = new IdentityServerUser(user.Id.ToString()) { AdditionalClaims = identityPricipal.Claims.ToArray(), DisplayName = user.UserName, AuthenticationTime = DateTime.UtcNow, IdentityProvider = IdentityServerConstants.LocalIdentityProvider }; request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new ValidatedRequest { Subject = request.Subject, }; var client = await ClientStore.FindClientByIdAsync(ClientId); request.ValidatedRequest.SetClient(client); request.Resources = new Resources(await ResourceStore.FindEnabledIdentityResourcesByScopeAsync(client.AllowedScopes), await ResourceStore.FindApiResourcesByScopeAsync(client.AllowedScopes)) { OfflineAccess = client.AllowOfflineAccess }; request.ValidatedRequest.Options = Options; request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims; var token = await TokenService.CreateAccessTokenAsync(request); var accessToken = await TokenService.CreateSecurityTokenAsync(token); var refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(request.Subject, token, client); return(new IdentityServerToken(token, accessToken, refreshToken)); }
private async Task SignInInternal(ApplicationUser user) { var props = new AuthenticationProperties(); var claims = new List <Claim>() { new Claim(Constants.Claims.MobileNumber, user.MobileNumber), new Claim(Constants.Claims.NationalCode, user.UserIdentityNumber), new Claim("given_name", user.FirstName), new Claim("family_name", user.LastName), }; var isuser = new IdentityServerUser(user.Id.ToString()) { DisplayName = $"{user.FirstName} {user.LastName}", AdditionalClaims = claims }; await _userManager.SetSuccessfulLogin(user); await _userManager.ResetAccessFailedCountAsync(user); var userPrincipal = isuser.CreatePrincipal(); await _httpContextAccessor.HttpContext.SignInAsync(Constants.DefaultAuthenticationSchemeName, userPrincipal, props); }
private async Task <Dictionary <string, string> > GenerateToken(UserModel user, string clientId, AccessTokenType accessTokenType = AccessTokenType.Reference) { var request = new TokenCreationRequest(); var identityUser = new IdentityServerUser(user.UserName); Dictionary <string, string> tokenResponse = null; string accessToken = null; string identityToken = null; string refreshToken = null; var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim("FirstName", user.FirstName), new Claim("LastName", user.LastName), new Claim("UserName", user.UserName) }; try { // Add Identity User information identityUser.DisplayName = user.FirstName + " " + user.LastName; identityUser.AuthenticationTime = DateTime.UtcNow; identityUser.IdentityProvider = IdentityServer4.IdentityServerConstants.LocalIdentityProvider; // Build Token Request information request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new IdentityServer4.Validation.ValidatedRequest { Subject = request.Subject, }; var clients = AuthenticationConfig.GetClients(); var client = clients.FirstOrDefault(item => item.ClientId == clientId) ?? throw new Exception("invalid client"); request.ValidatedRequest.SetClient(client); request.ValidatedResources = new IdentityServer4.Validation.ResourceValidationResult { Resources = new Resources(AuthenticationConfig.GetIdentityResources(), AuthenticationConfig.GetApiResources(), AuthenticationConfig.GetApiScopes()) }; Token accessTokenObj = null; if (accessTokenType == AccessTokenType.Reference) { accessTokenObj = await _tokenService.CreateAccessTokenAsync(request); accessTokenObj.Issuer = AuthenticationConfig.authority; foreach (var claim in claims) { accessTokenObj.Claims.Add(claim); } accessToken = await _tokenService.CreateSecurityTokenAsync(accessTokenObj); } var principal = new ClaimsPrincipal(); refreshToken = await _refreshTokenService.CreateRefreshTokenAsync(principal, accessTokenObj, client); tokenResponse = new Dictionary <string, string> { { "access_token", accessToken }, }; if (refreshToken != null) { tokenResponse.Add("refresh_token", refreshToken); } } catch (Exception e) { tokenResponse = null; } return(tokenResponse); }
/// <summary> /// Signs the user in. /// </summary> /// <param name="context">The manager.</param> /// <param name="user">The IdentityServer user.</param> /// <param name="properties">The authentication properties.</param> /// <returns></returns> public static async Task SignInAsync(this HttpContext context, IdentityServerUser user, AuthenticationProperties properties) { await context.SignInAsync(await context.GetCookieAuthenticationSchemeAsync(), user.CreatePrincipal(), properties); }
public async Task <IActionResult> Login([FromForm] LoginViewModel viewModel) { LinUser user = await userRepository.GetUserAsync(r => r.Username == viewModel.Username || r.Email == viewModel.Username); if (user == null) { ModelState.AddModelError("", "用户不存在"); viewModel.Password = string.Empty; return(View("/Views/Login.cshtml", viewModel)); } bool valid = await userIdentityService.VerifyUserPasswordAsync(user.Id, viewModel.Password); if (!valid) { ModelState.AddModelError("", "Invalid username or password"); viewModel.Password = string.Empty; return(View("/Views/Login.cshtml", viewModel)); } // Use an IdentityServer-compatible ClaimsPrincipal var identityServerUser = new IdentityServerUser(viewModel.Username); identityServerUser.DisplayName = viewModel.Username; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identityServerUser.CreatePrincipal()); return(Redirect(viewModel.ReturnUrl)); }
public async Task <string> GetAccessTokenAsync(UserModel user, List <Claim> additionalClientClaims = null) { try { var tokenCreationRequest = new TokenCreationRequest(); var identityPricipal = await _principalFactory.CreateAsync(user).ConfigureAwait(false); var identityUser = new IdentityServerUser(user.Id.ToString()); identityUser.AdditionalClaims = identityPricipal.Claims.ToArray(); identityUser.DisplayName = user.UserName; identityUser.AuthenticationTime = DateTime.UtcNow; identityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider; var subject = identityUser.CreatePrincipal(); tokenCreationRequest.Subject = subject; tokenCreationRequest.IncludeAllIdentityClaims = true; tokenCreationRequest.ValidatedRequest = new ValidatedRequest(); tokenCreationRequest.ValidatedRequest.Subject = tokenCreationRequest.Subject; string defaultClientId = _configurationProvider.DefaultClientId; var client = await _clientStore.FindClientByIdAsync(defaultClientId).ConfigureAwait(false); tokenCreationRequest.ValidatedRequest.SetClient(client); var resources = await _resourceStore.GetAllEnabledResourcesAsync().ConfigureAwait(false); tokenCreationRequest.Resources = resources; tokenCreationRequest.ValidatedRequest.Options = _options; if (additionalClientClaims != null) { foreach (Claim additionalClientClaim in additionalClientClaims) { tokenCreationRequest.ValidatedRequest.ClientClaims.Add(additionalClientClaim); } } var accessToken = await CreateAccessTokenAsync(tokenCreationRequest).ConfigureAwait(false); string defaultClientAuthority = _configurationProvider.DefaultClientAuthority; accessToken.Issuer = defaultClientAuthority; var accessTokenValue = await _tokenService.CreateSecurityTokenAsync(accessToken).ConfigureAwait(false); return(accessTokenValue); } catch (ApiException e) { throw e; } catch (Exception e) { _logger.LogError($"Error when getting access token: {e}"); throw new InternalServerErrorApiException(); } }
/// <summary> /// Internal signin method that generates the cookie authentication for an UserResult in the NudesIdentity schema /// </summary> internal static Task SignInAsync(this HttpContext context, UserResult user, AuthenticationProperties properties) { var clock = context.RequestServices.GetRequiredService <ISystemClock>(); var identityUser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username, AuthenticationTime = clock.UtcNow.UtcDateTime, }; if (user.Claims != null) { identityUser.AdditionalClaims = user.Claims; } return(context.SignInAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme, identityUser.CreatePrincipal(), properties)); }
public async Task <IActionResult> Login([FromForm] LoginViewModel viewModel) { if (!_userStore.ValidateCredentials(viewModel.Username, viewModel.Password)) { ModelState.AddModelError("", "Invalid username or password"); viewModel.Password = string.Empty; return(View("/AuthServer/Views/Login.cshtml", viewModel)); } // Use an IdentityServer-compatible ClaimsPrincipal var identityServerUser = new IdentityServerUser(viewModel.Username); identityServerUser.DisplayName = viewModel.Username; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identityServerUser.CreatePrincipal()); return(Redirect(viewModel.ReturnUrl)); }