public async Task <IActionResult> AddUserRole([FromRoute] string userId, [FromRoute] string roleId) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound()); } var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return(NotFound()); } if (await _userManager.IsInRoleAsync(user, role.Name)) { return(BadRequest(new ValidationProblemDetails(new Dictionary <string, string[]> { { $"{nameof(roleId)}", new[] { $"User {user.Email} is already a member of role {role.Name}." } } }))); } var result = await _userManager.AddToRoleAsync(user, role.Name); if (!result.Succeeded) { return(BadRequest(result.Errors.ToValidationProblemDetails())); } if (role.IsManagementRole()) { var clientId = User.FindFirst(JwtClaimTypes.ClientId); await _persistedGrantService.RemoveAllGrantsAsync(userId, clientId?.Value); } return(NoContent()); }
public async Task <IActionResult> Logout(LogoutViewModel model) { var user = HttpContext.User.Identity.Name; var subjectId = HttpContext.User.Identity.GetSubjectId(); // delete authentication cookie await HttpContext.Authentication.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); var vm = new LoggedOutViewModel { PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = logout?.ClientId, SignOutIframeUrl = logout?.SignOutIFrameUrl }; await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "WanVetClientDev"); await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "WanVetClient"); return(View("LoggedOut", vm)); }
public async Task RevokeUserConsentAsync(string clientId) { var user = await _context.HttpContext.GetIdentityServerUserAsync(); if (user != null) { var subject = user.GetSubjectId(); await _grants.RemoveAllGrantsAsync(subject, clientId); } }
public async Task RevokeUserConsentAsync(string clientId) { var user = await _userSession.GetUserAsync(); if (user != null) { var subject = user.GetSubjectId(); await _grants.RemoveAllGrantsAsync(subject, clientId); } }
public async Task RevokeUserConsentAsync(string clientId) { using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultIdentityServerInteractionService.RevokeUserConsent"); var user = await _userSession.GetUserAsync(); if (user != null) { var subject = user.GetSubjectId(); await _grants.RemoveAllGrantsAsync(subject, clientId); } }
/// <inheritdoc/> public async Task RemoveAllGrantsAsync(string subjectId, string clientId = null, string sessionId = null) { var removedGrants = await _persistedGrantDbContext.PersistedGrants.Where(x => x.SubjectId == subjectId && x.ClientId == clientId).ToListAsync(); await _inner.RemoveAllGrantsAsync(subjectId, clientId); var consents = removedGrants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.UserConsent); var scopeValues = new List <string>(); foreach (var consent in consents) { var consentData = _serializer.Deserialize <Consent>(consent.Data); if (consentData?.Scopes != null && consentData.Scopes.Any()) { scopeValues.AddRange(consentData.Scopes); } } var parsedScopesResult = _scopeParser.ParseScopeValues(scopeValues); if (!parsedScopesResult.Succeeded) { return; } await _parsedScopeNotificationService.Notify(clientId, parsedScopesResult.ParsedScopes, ParsedScopeNotificationType.GrantsRevoked); }
public async Task ExecuteAsync(LogoutCommand command, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (cancellationToken.IsCancellationRequested) { _logger.LogInformation($"{nameof(LogoutCommandHandler)}.{nameof(ExecuteAsync)} was cancelled before execution"); cancellationToken.ThrowIfCancellationRequested(); } await _signInManager.SignOutAsync(); var logout = await _interaction.GetLogoutContextAsync(command.LogoutId); await _persistedGrantService.RemoveAllGrantsAsync(command.Subject, logout?.ClientId); var aggregate = await _aggregateRepository.GetAsync <User, UserState>(command.Subject, cancellationToken); var expectedVersion = aggregate.Version; if (aggregate == null) { throw new ArgumentNullException(nameof(aggregate)); } aggregate.Logout(); await _aggregateRepository.SaveAsync(aggregate, command, expectedVersion, cancellationToken); }
public async Task <IActionResult> Logout(LogoutInputModel model) { if (User?.Identity.IsAuthenticated == true) { var subjectId = HttpContext.User.Identity.GetSubjectId(); // delete local authentication cookie await _signInManager.SignOutAsync(); var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); var vm = await BuildLoggedOutViewModelAsync(model.LogoutId); await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout?.ClientId); if (!string.IsNullOrEmpty(vm.PostLogoutRedirectUri)) { return(Redirect(vm.PostLogoutRedirectUri)); } return(View("LoggedOut", vm)); } return(RedirectToAction(nameof(HomeController.Index), "Home")); }
public async Task <IActionResult> Logout(LogoutViewModel model) { var idp = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; var subjectId = User?.FindFirst(JwtClaimTypes.Subject)?.Value; if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { if (model.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout model.LogoutId = await _interaction.CreateLogoutContextAsync(); } string url = "/Account/Logout?logoutId=" + model.LogoutId; try { await _signInManager.SignOutAsync(); // await HttpContext.Authentication.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (NotSupportedException) { } } // delete authentication cookie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); var vm = new LoggedOutViewModel { PostLogoutRedirectUri = logout?.PostLogoutRedirectUri != null ? logout?.PostLogoutRedirectUri : "/", AutomaticRedirectAfterSignOut = true, ClientName = logout?.ClientId, SignOutIframeUrl = logout?.SignOutIFrameUrl }; if (subjectId != null) { var grants = await _persistedGrantService.GetAllGrantsAsync(subjectId); foreach (var grant in grants) { await _persistedGrantService.RemoveAllGrantsAsync(subjectId, grant.ClientId); } } return(View("LoggedOut", vm)); }
/// <summary> /// 注销 /// </summary> /// <returns></returns> //[AllowAnonymous] public async Task <IActionResult> Logout() { var subjectId = HttpContext.User.Identity.GetSubjectId(); await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "DangguiSite"); //var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); //var userID = await GetUserID(token); //SetCache(userID); return(View("Index")); }
private async Task <LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId) { // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(logoutId); var subjectId = HttpContext.User.Identity.GetSubjectId(); var vm = new LoggedOutViewModel { AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut, PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName, SignOutIframeUrl = logout?.SignOutIFrameUrl, LogoutId = logoutId }; if (User?.Identity.IsAuthenticated == true) { var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider) { var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp); if (providerSupportsSignout) { if (vm.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout vm.LogoutId = await _interaction.CreateLogoutContextAsync(); } try { await _signInManager.SignOutAsync(); // await HttpContext.Authentication.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (NotSupportedException) { } vm.ExternalAuthenticationScheme = idp; } } // delete authentication cookie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout?.ClientId); } return(vm); }
public async Task <IActionResult> OnPost(string logoutId) { LogoutId = logoutId; var idProvider = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; var subjectId = HttpContext.User.Identity.GetSubjectId(); if (idProvider != null && idProvider != IdentityServerConstants.LocalIdentityProvider) { if (logoutId is null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout LogoutId = await _interaction.CreateLogoutContextAsync(); } string url = "/Logout/Logout?logoutId=" + logoutId; try { await _signInManager.SignOutAsync(); // await HttpContext.Authentication.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (NotSupportedException) { } } // delete authentication cookie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(LogoutId); PostLogoutRedirectUri = logout?.PostLogoutRedirectUri; ClientName = logout?.ClientId; SignOutIframeUrl = logout?.SignOutIFrameUrl; //_clientSelector.SelectedClient = logout?.ClientId; await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout?.ClientId); //return View($"~/Themes/{logout?.ClientId}/Account/LoggedOut.cshtml", vm); return(Page()); }
public async Task <IActionResult> Logout() { if (!User.IsAuthenticated()) { return(RedirectToAction("Login")); } var user = HttpContext.User.Identity.Name; var sub = HttpContext.User.Identity.GetSubjectId(); // delete authentication cookie await HttpContext.Authentication.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); await _persistedGrantService.RemoveAllGrantsAsync(sub, "client"); await signInManager.SignOutAsync(); return(RedirectToAction(nameof(HomeController.Index), "Home")); }
public async Task <IActionResult> Logout(LogoutViewModel model) { await FullLogOut().ConfigureAwait(false); var idp = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; var subjectId = HttpContext.User.Identity.GetSubjectId(); if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { if (model.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout model.LogoutId = await _interaction.CreateLogoutContextAsync().ConfigureAwait(false); } try { await _signInManager.SignOutAsync().ConfigureAwait(false); } catch (NotSupportedException) { } } // delete authentication cookie await _signInManager.SignOutAsync().ConfigureAwait(false); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId).ConfigureAwait(false); var vm = new LoggedOutViewModel { PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = logout?.ClientId, SignOutIframeUrl = logout?.SignOutIFrameUrl }; await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout.ClientId).ConfigureAwait(false); return(View("LoggedOut", vm)); }
public async Task <IActionResult> Logout(LogoutViewModel model) { var idp = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; var subjectId = HttpContext.User.Identity.GetSubjectId(); if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { if (model.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout model.LogoutId = await _interaction.CreateLogoutContextAsync(); } string url = "/Account/Logout?logoutId=" + model.LogoutId; try { // hack: try/catch to handle social providers that throw await HttpContext.Authentication.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (NotSupportedException) { } } // delete authentication cookie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); var vm = new LoggedOutViewModel { PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = logout?.ClientId, SignOutIframeUrl = logout?.SignOutIFrameUrl }; await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout?.ClientId ?? "spa-client"); return(Redirect(logout?.PostLogoutRedirectUri ?? "http://localhost:8080")); }
public async Task <IActionResult> Logout([FromBody] LogOutRequest model) { var subjectId = HttpContext.User.Identity.GetSubjectId(); // delete authentication cookie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for // federated signout) await _persistedGrantService.RemoveAllGrantsAsync(subjectId, model.ClientName); return(Ok()); }
public async Task <IActionResult> Logout(LogoutViewModel model) { var idp = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; var subjectId = HttpContext.User.Identity.GetSubjectId(); if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { if (model.LogoutId == null) { model.LogoutId = await _interaction.CreateLogoutContextAsync(); } string url = "/Account/Logout?logoutId=" + model.LogoutId; try { await HttpContext.Authentication.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (NotSupportedException) { } } // delete authentication cockie await _signInManager.SignOutAsync(); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect uri and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("PostlogoutUri: " + logout?.PostLogoutRedirectUri); var vm = new LoggedOutViewModel { PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, ClientName = logout?.ClientId, SignOutIframeUrl = logout?.SignOutIFrameUrl }; await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "HawaiProjectClient"); // return Redirect(logout?.PostLogoutRedirectUri); return(View("LoggedOutViewModel", vm)); }
/// <summary> /// Removes all grants for a given subject id and client id combination. /// </summary> /// <param name="subjectId">The subject identifier.</param> /// <param name="clientId">The client identifier.</param> public async Task RemoveAllGrantsAsync(string subjectId, string clientId) { var grants = await _persistedGrantDbContext.PersistedGrants.Where(x => x.SubjectId == subjectId && x.ClientId == clientId).ToListAsync(); await _inner.RemoveAllGrantsAsync(subjectId, clientId); var consents = grants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.UserConsent); var scopes = new List <string>(); foreach (var consent in consents) { var consentData = _serializer.Deserialize <Consent>(consent.Data); if (consentData?.Scopes != null && consentData.Scopes.Any()) { scopes.AddRange(consentData.Scopes); } } await _dynamicScopeNotificationService.Notify(clientId, scopes, DynamicScopeNotificationType.GrantsRevoked); }
public async Task <IActionResult> SetUserBlock([FromRoute] string userId, [FromBody] SetUserBlockRequest request) { var user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id == userId); if (user == null) { return(NotFound()); } user.Blocked = request.Blocked; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { return(BadRequest(result.Errors.AsValidationProblemDetails())); } // When blocking a user we need to make sure we also revoke all of his tokens. await _persistedGrantService.RemoveAllGrantsAsync(userId); return(NoContent()); }
public async Task <IActionResult> Logout(LogoutViewModel model) { var subjectId = HttpContext.User.Identity.GetSubjectId(); var vm = new LoggedOutViewModel { LogoutId = model.LogoutId }; if (User?.Identity.IsAuthenticated == true) { var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider) { var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp); if (providerSupportsSignout) { //if (vm.LogoutId == null) //{ // // if there's no current logout context, we need to create one // // this captures necessary info from the current logged in user // // before we signout and redirect away to the external IdP for signout // vm.LogoutId = await _interaction.CreateLogoutContextAsync(); //} vm.ExternalAuthenticationScheme = idp; } } } if (vm.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout vm.LogoutId = await _interaction.CreateLogoutContextAsync(); } if (User?.Identity.IsAuthenticated == true) { // delete local authentication cookie await _signInManager.SignOutAsync(); // raise the logout event await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); } // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(vm.LogoutId); vm.AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut; vm.PostLogoutRedirectUri = logout?.PostLogoutRedirectUri; vm.ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName; vm.SignOutIframeUrl = logout?.SignOutIFrameUrl; if (logout?.ClientId != null) { //await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "singleapp"); await _persistedGrantService.RemoveAllGrantsAsync(subjectId, logout?.ClientId); } //check if we need to trigger sign-out at an upstream identity provider if (vm.TriggerExternalSignout) { // build a return URL so the upstream provider will redirect back // to us after the user has logged out. this allows us to then // complete our single sign-out processing. string url = Url.Action("Logout", new { logoutId = vm.LogoutId }); // this triggers a redirect to the external provider for sign-out return(SignOut(new Microsoft.AspNetCore.Authentication.AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme)); } if (string.IsNullOrWhiteSpace(vm.PostLogoutRedirectUri)) { return(View("LoggedOut", vm)); } else { return(Redirect(vm.PostLogoutRedirectUri)); } }
public async Task <IActionResult> Logout(LogoutViewModel model) { Console.WriteLine("Test 1.1"); var idp = User?.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; Console.WriteLine("Test 1.2"); Console.WriteLine(idp); var subjectId = HttpContext.User.Identity.GetSubjectId(); Console.WriteLine("Test 1.3"); Console.WriteLine(subjectId); if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { Console.WriteLine("Test 1.4"); if (model.LogoutId == null) { // if there's no current logout context, we need to create one // this captures necessary info from the current logged in user // before we signout and redirect away to the external IdP for signout Console.WriteLine("Test 1.5"); model.LogoutId = await _interaction.CreateLogoutContextAsync(); } string url = "/Account/Logout?logoutId=" + model.LogoutId; try { Console.WriteLine("Test 1.6"); // hack: try/catch to handle social providers that throw await HttpContext.SignOutAsync(idp, new AuthenticationProperties { RedirectUri = url }); } catch (Exception ex) { Console.WriteLine("Test 1.7"); _logger.LogCritical(ex.Message); } } Console.WriteLine("Test 1.8"); // delete authentication cookie await HttpContext.SignOutAsync(); await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme); // set this so UI rendering sees an anonymous user HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Console.WriteLine("Test 1.9"); // get context information (client name, post logout redirect URI and iframe for federated signout) var logout = await _interaction.GetLogoutContextAsync(model.LogoutId); Console.WriteLine("Test 1.9.1"); //// full user logout. Every time new credentials will be required. await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "nova_mobile"); return(Redirect(logout?.PostLogoutRedirectUri)); }