List of usage examples for org.springframework.security.core.context SecurityContextHolder clearContext
public static void clearContext()
From source file:org.cloudfoundry.identity.uaa.authentication.BackwardsCompatibleTokenEndpointAuthenticationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try {/* www . ja v a2 s .co m*/ Authentication userAuthentication = extractCredentials(request, response); if (userAuthentication != null) { Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication(); if (clientAuth == null) { throw new BadCredentialsException( "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter."); } Map<String, String> map = getSingleValueMap(request); map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName()); SecurityContextHolder.getContext().setAuthentication(userAuthentication); AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map); //authorizationRequest.setScope(getScope(request)); if (clientAuth.isAuthenticated()) { // Ensure the OAuth2Authentication is authenticated authorizationRequest.setApproved(true); } OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest); SecurityContextHolder.getContext() .setAuthentication(new OAuth2Authentication(storedOAuth2Request, userAuthentication)); onSuccessfulAuthentication(request, response, userAuthentication); } } catch (UnauthorizedClientException failed) { //happens when all went well, but the client is not authorized for the identity provider UnapprovedClientAuthenticationException ex = new UnapprovedClientAuthenticationException( failed.getMessage(), failed); SecurityContextHolder.clearContext(); logger.debug("Authentication request for failed: " + failed); onUnsuccessfulAuthentication(request, response, ex); authenticationEntryPoint.commence(request, response, ex); return; } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); logger.debug("Authentication request for failed: " + failed); onUnsuccessfulAuthentication(request, response, failed); authenticationEntryPoint.commence(request, response, failed); return; } catch (InvalidScopeException ex) { String message = ex.getMessage(); response.sendError(UNAUTHORIZED.value(), message); return; } chain.doFilter(request, response); }
From source file:org.cloudfoundry.identity.uaa.login.EmailChangeEmailServiceTest.java
@AfterEach public void tearDown() throws Exception { SecurityContextHolder.clearContext(); IdentityZoneHolder.clear(); }
From source file:org.cloudfoundry.identity.uaa.login.EmailChangeEmailServiceTest.java
@BeforeEach public void setUp() throws Exception { SecurityContextHolder.clearContext(); scimUserProvisioning = mock(ScimUserProvisioning.class); codeStore = mock(ExpiringCodeStore.class); clientDetailsService = mock(MultitenantClientServices.class); messageService = mock(EmailService.class); emailChangeEmailService = new EmailChangeEmailService(templateEngine, messageService, scimUserProvisioning, codeStore, clientDetailsService); request = new MockHttpServletRequest(); request.setProtocol("http"); request.setContextPath("/login"); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); }
From source file:org.cloudfoundry.identity.uaa.login.saml.SamlIDPRefreshMockMvcTests.java
@Before public void setUpContext() throws Exception { SecurityContextHolder.clearContext(); testAccounts = UaaTestAccounts.standard(null); jdbcTemplate = getWebApplicationContext().getBean(JdbcTemplate.class); providerProvisioning = getWebApplicationContext().getBean(IdentityProviderProvisioning.class); zoneAwareMetadataManager = getWebApplicationContext().getBean(ZoneAwareMetadataManager.class); zoneProvisioning = getWebApplicationContext().getBean(IdentityZoneProvisioning.class); configurator = getWebApplicationContext().getBean(IdentityProviderConfigurator.class); //ensure that we don't fire the listener, we want to test the DB refresh getWebApplicationContext().getBean(ProviderChangedListener.class).setMetadataManager(null); cleanSamlProviders();// ww w.j a v a2 s . co m }
From source file:org.cloudfoundry.identity.uaa.login.saml.SamlIDPRefreshMockMvcTests.java
@After public void cleanSamlProviders() throws Exception { for (IdentityZone zone : zoneProvisioning.retrieveAll()) { for (IdentityProvider provider : providerProvisioning.retrieveAll(false, zone.getId())) { if (Origin.SAML.equals(provider.getType())) { ZoneAwareMetadataManager.ExtensionMetadataManager manager = zoneAwareMetadataManager .getManager(zone); IdentityProviderDefinition definition = provider .getConfigValue(IdentityProviderDefinition.class); ExtendedMetadataDelegate delegate = configurator .getExtendedMetadataDelegateFromCache(definition); configurator.removeIdentityProviderDefinition(definition); if (delegate != null) { manager.removeMetadataProvider(delegate); }/*from w ww.j ava 2 s . co m*/ jdbcTemplate.update("delete from identity_provider where id='" + provider.getId() + "'"); } } getMockMvc().perform(post("/saml/metadata") .with(new SetServerNameRequestPostProcessor(zone.getSubdomain() + ".localhost"))); //all we have left is the local provider assertEquals(1, zoneAwareMetadataManager.getManager(zone).getAvailableProviders().size()); } SecurityContextHolder.clearContext(); IdentityZoneHolder.clear(); }
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java
@AfterEach public void clearContext() { SecurityContextHolder.clearContext(); IdentityZoneHolder.clear(); }
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java
@BeforeEach public void setUp() throws Exception { RestTemplateConfig restTemplateConfig = new RestTemplateConfig(); RestTemplate nonTrustingRestTemplate = restTemplateConfig.nonTrustingRestTemplate(); RestTemplate trustingRestTemplate = restTemplateConfig.trustingRestTemplate(); SecurityContextHolder.clearContext(); IdentityZoneHolder.clear();//from w w w.ja va 2 s. c o m String keyName = "testKey"; header = map(entry("alg", "HS256"), entry("kid", keyName), entry("typ", "JWT")); signer = new RsaSigner(PRIVATE_KEY); IdentityZoneHolder.get().getConfig().getTokenPolicy() .setKeys(Collections.singletonMap(keyName, PRIVATE_KEY)); provisioning = mock(IdentityProviderProvisioning.class); ScimGroupExternalMembershipManager externalMembershipManager = mock( ScimGroupExternalMembershipManager.class); for (String scope : SCOPES_LIST) { ScimGroupExternalMember member = new ScimGroupExternalMember(); member.setDisplayName(scope); when(externalMembershipManager.getExternalGroupMapsByExternalGroup(eq(scope), anyString(), anyString())) .thenReturn(Collections.singletonList(member)); } userDatabase = new InMemoryUaaUserDatabase(Collections.emptySet()); publisher = mock(ApplicationEventPublisher.class); tokenEndpointBuilder = mock(TokenEndpointBuilder.class); when(tokenEndpointBuilder.getTokenEndpoint()).thenReturn(UAA_ISSUER_URL); OidcMetadataFetcher oidcMetadataFetcher = new OidcMetadataFetcher( new ExpiringUrlCache(Duration.ofMinutes(2), new TimeServiceImpl(), 10), trustingRestTemplate, nonTrustingRestTemplate); xoAuthProviderConfigurator = spy(new XOAuthProviderConfigurator(provisioning, oidcMetadataFetcher)); xoAuthAuthenticationManager = spy( new XOAuthAuthenticationManager(xoAuthProviderConfigurator, trustingRestTemplate, nonTrustingRestTemplate, tokenEndpointBuilder, new KeyInfoService(UAA_ISSUER_URL))); xoAuthAuthenticationManager.setUserDatabase(userDatabase); xoAuthAuthenticationManager.setExternalMembershipManager(externalMembershipManager); xoAuthAuthenticationManager.setApplicationEventPublisher(publisher); xoAuthAuthenticationManager.setTokenEndpointBuilder(tokenEndpointBuilder); xCodeToken = new XOAuthCodeToken(CODE, ORIGIN, "http://localhost/callback/the_origin"); claims = map(entry("sub", "12345"), entry("preferred_username", "marissa"), entry("origin", UAA_ORIGIN), entry("iss", "http://localhost/oauth/token"), entry("given_name", "Marissa"), entry("client_id", "client"), entry("aud", Arrays.asList("identity", "another_trusted_client")), entry("zid", "uaa"), entry("user_id", "12345"), entry("azp", "client"), entry("scope", Collections.singletonList("openid")), entry("auth_time", 1458603913), entry("phone_number", "1234567890"), entry("exp", Instant.now().getEpochSecond() + 3600), entry("iat", 1458603913), entry("family_name", "Bloggs"), entry("jti", "b23fe183-158d-4adc-8aff-65c440bbbee1"), entry("email", "marissa@bloggs.com"), entry("rev_sig", "3314dc98"), entry("cid", "client"), entry("email_verified", true), entry(ClaimConstants.ACR, JsonUtils.readValue( "{\"values\": [\"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\"] }", Map.class))); attributeMappings = new HashMap<>(); config = new OIDCIdentityProviderDefinition().setAuthUrl(new URL("http://localhost/oauth/authorize")) .setTokenUrl(new URL("http://localhost/oauth/token")).setIssuer("http://localhost/oauth/token") .setShowLinkText(true).setLinkText("My OIDC Provider").setRelyingPartyId("identity") .setRelyingPartySecret("identitysecret").setUserInfoUrl(new URL("http://localhost/userinfo")) .setTokenKey(PUBLIC_KEY); config.setExternalGroupsWhitelist(Collections.singletonList("*")); mockUaaServer = MockRestServiceServer.createServer(nonTrustingRestTemplate); invalidRsaSigningKey = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIBOgIBAAJBAJnlBG4lLmUiHslsKDODfd0MqmGZRNUOhn7eO3cKobsFljUKzRQe\n" + "GB7LYMjPavnKccm6+jWSXutpzfAc9A9wXG8CAwEAAQJADwwdiseH6cuURw2UQLUy\n" + "sVJztmdOG6b375+7IMChX6/cgoF0roCPP0Xr70y1J4TXvFhjcwTgm4RI+AUiIDKw\n" + "gQIhAPQHwHzdYG1639Qz/TCHzuai0ItwVC1wlqKpat+CaqdZAiEAoXFyS7249mRu\n" + "xtwRAvxKMe+eshHvG2le+ZDrM/pz8QcCIQCzmCDpxGL7L7sbCUgFN23l/11Lwdex\n" + "uXKjM9wbsnebwQIgeZIbVovUp74zaQ44xT3EhVwC7ebxXnv3qAkIBMk526sCIDVg\n" + "z1jr3KEcaq9zjNJd9sKBkqpkVSqj8Mv+Amq+YjBA\n" + "-----END RSA PRIVATE KEY-----"; }
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerTest.java
@Before @After// w w w . j a va2 s . c o m public void clearContext() { SecurityContextHolder.clearContext(); header = map(entry("alg", "HS256"), entry("kid", "testKey"), entry("typ", "JWT")); }
From source file:org.encuestame.business.service.SecurityService.java
/** * Update Account Profile./*from w w w .j a va2 s .c o m*/ * @param bio * @param email * @param username * @param language * @param completeName * @throws EnMeNoResultsFoundException */ public void updateAccountProfile(final String bio, final String language, final String completeName, final String username, final String email) throws EnMeNoResultsFoundException { final UserAccount account = getUserAccount(getUserPrincipalUsername()); if (log.isDebugEnabled()) { log.debug("update Account user to update " + account.getUsername()); log.debug("update Account Profile bio " + bio); log.debug("update Account Profile language " + language); log.debug("update Account Profile username " + username); } account.setCompleteName(completeName); account.setUserEmail(email); account.setUsername(username); account.setLanguage(language == null ? new Locale(EnMeUtils.DEFAULT_LANG).getLanguage() : new Locale(language).getLanguage()); getAccountDao().saveOrUpdate(account); //clear the security context SecurityContextHolder.clearContext(); // login the user SecurityUtils.authenticate(account); }
From source file:org.encuestame.core.security.web.SecurityUtils.java
/** * * @param account/* w ww . j av a2 s . c o m*/ * @param password * @param socialSignIn */ public static void socialAuthentication(final SocialAccount accountConnection) { final UserAccount account = accountConnection.getUserOwner(); log.trace("Register SOCIAL LOGIN USER: " + account.getUsername()); // building granted authorities final Collection<GrantedAuthority> authorities = ConvertDomainsToSecurityContext .convertEnMePermission(account.getSecUserPermissions()); // create user detail based on user account. final EnMeSocialUserAccount details = SecurityUtils.convertUserAccountToUserDetails(accountConnection); // set the social credentials permission. details.setSocialCredentials(true); final SocialAuthenticationToken token = new SocialAuthenticationToken(details, authorities); token.setProfileId(accountConnection.getSocialProfileId()); token.setProvider(accountConnection.getAccounType()); //clear the context. SecurityContextHolder.clearContext(); //set new authentication. SecurityContextHolder.getContext().setAuthentication(token); if (log.isInfoEnabled()) { log.info("Username " + account.getUsername() + " is logged at " + new Date()); log.debug("created EnMeSocialUserAccount" + details); } }