Java Code Examples for org.springframework.security.core.context.SecurityContextHolder#clearContext()

The following examples show how to use org.springframework.security.core.context.SecurityContextHolder#clearContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringAuthManager.java    From jdal with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(String username, String password) {
	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
	try {
		Authentication auth = this.authenticationManager.authenticate(token);
		if (auth.isAuthenticated()) {
			// execute session authentication strategy
			if (this.sessionStrategy != null)
				this.sessionStrategy.onAuthentication(auth, VaadinServletService.getCurrentServletRequest(),
						VaadinServletService.getCurrentResponse());
			SecurityContextHolder.getContext().setAuthentication(auth);
			// save request in context session
			VaadinSession.getCurrent().getSession().setAttribute(
					HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
					SecurityContextHolder.getContext());
			
			return  true;
		}
		SecurityContextHolder.clearContext();
		return false;
	}
	catch(AuthenticationException ae) {
		SecurityContextHolder.clearContext();
		return false;
	}
}
 
Example 2
Source File: LogoutController.java    From auth-server with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * One click logout. Invalidates the session.
 * </p>
 */
@PostMapping("/logout")
public String logout(HttpServletRequest request) {
  log.debug("Direct logout");

  // Current user was validated -> Clear securityContext
  SecurityContextHolder.getContext().setAuthentication(null);
  SecurityContextHolder.clearContext();

  // Invalidate session
  final HttpSession session = request.getSession(false);
  if (session != null) {
    session.invalidate();
  }

  return "redirect:/login?logout";
}
 
Example 3
Source File: ApiCatalogLogoutSuccessHandler.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Clears cookie, session, context and sets response code
 *
 * @param httpServletRequest  Http request
 * @param httpServletResponse Http response
 * @param authentication      Valid authentication
 */
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                            Authentication authentication) {
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    // Set the cookie to null and expired
    Cookie tokenCookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), null);
    tokenCookie.setPath(authConfigurationProperties.getCookieProperties().getCookiePath());
    tokenCookie.setComment(authConfigurationProperties.getCookieProperties().getCookieComment());
    tokenCookie.setSecure(true);
    tokenCookie.setHttpOnly(true);
    tokenCookie.setMaxAge(0);
    httpServletResponse.addCookie(tokenCookie);

    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(null);
    SecurityContextHolder.clearContext();
}
 
Example 4
Source File: Application.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Pre-load the system with employees and items.
 */
public @PostConstruct void init() {

	employeeRepository.save(new Employee("Bilbo", "Baggins", "thief"));
	employeeRepository.save(new Employee("Frodo", "Baggins", "ring bearer"));
	employeeRepository.save(new Employee("Gandalf", "the Wizard", "servant of the Secret Fire"));

	/**
	 * Due to method-level protections on {@link example.company.ItemRepository}, the security context must be loaded
	 * with an authentication token containing the necessary privileges.
	 */
	SecurityUtils.runAs("system", "system", "ROLE_ADMIN");

	itemRepository.save(new Item("Sting"));
	itemRepository.save(new Item("the one ring"));

	SecurityContextHolder.clearContext();
}
 
Example 5
Source File: ApplicationResourceTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyGetAsAdmin() throws URISyntaxException {
    EntityBody toGet = getNewApp();
    // Mock repo can't do real queries for arrays.
    when(uriInfo.getRequestUri()).thenReturn(new URI("http://some.net/api/rest/apps/"));
    Response created = resource.post(toGet, uriInfo);
    assertEquals(STATUS_CREATED, created.getStatus());
    toGet.put(ApplicationResource.AUTHORIZED_ED_ORGS, "3333-3333-3333");
    String uuid = parseIdFromLocation(created);
    when(uriInfo.getRequestUri()).thenReturn(new URI("http://some.net/api/rest/apps/" + uuid));
    created = unversionedResource.put(uuid, toGet, uriInfo);
    assertEquals(STATUS_NO_CONTENT, created.getStatus());
    SecurityContextHolder.clearContext();
    injector.setAdminContextWithElevatedRights();
    when(uriInfo.getRequestUri()).thenReturn(new URI("http://some.net/api/rest/apps/"));
    Response resp = resource.getAll(uriInfo);
    assertEquals(STATUS_FOUND, resp.getStatus());
    EntityResponse entityResponse = (EntityResponse) resp.getEntity();
    @SuppressWarnings("unchecked")
    List<EntityBody> bodies = (List<EntityBody>) entityResponse.getEntity();
    assertTrue(bodies.size() == 0);
}
 
Example 6
Source File: ApplicationResourceTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void approveApplication() throws URISyntaxException {
    //Create - Approve
    EntityBody app = getNewApp();
    when(uriInfo.getRequestUri()).thenReturn(new URI("http://some.net/api/rest/apps/"));
    Response created = resource.post(app, uriInfo);
    SecurityContextHolder.clearContext();
    injector.setOperatorContext();
    String uuid = parseIdFromLocation(created);
    Map registration = getRegistrationDataForApp(uuid);
    registration.put(STATUS, "APPROVED");
    app.put(REGISTRATION, registration);
    when(uriInfo.getRequestUri()).thenReturn(new URI("http://some.net/api/rest/apps/" + uuid));
    assertEquals(STATUS_NO_CONTENT, resource.put(uuid, app, uriInfo).getStatus());
    Map reg = getRegistrationDataForApp(uuid);
    assertTrue("approval date set", reg.containsKey(APPROVAL_DATE));
}
 
Example 7
Source File: UserConverter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(ILoggingEvent event) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        Object oPrincipal = auth.getPrincipal();
        String principal = "";
        if (oPrincipal != null) {
            principal = oPrincipal.toString();
        }
        return principal;

    } else {
        //calling getContext when there is no context creates a new security context
        //ThreadLocal that's never cleaned up otherwise
        SecurityContextHolder.clearContext();
    }
    return "NO_USER";
}
 
Example 8
Source File: LoginAuthenticationFilterTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Test
void doFilter() throws IOException, ServletException {
    // Given
    SecurityContextHolder.clearContext();
    when(request.getHeader("login")).thenReturn("anton.brueckner");
    when(request.getHeader("pin")).thenReturn("12345");
    when(userMgmtRestClient.authorise(anyString(), anyString(), any())).thenReturn(ResponseEntity.ok(getScaLoginResponse()));

    // When
    filter.doFilter(request, response, chain);

    // Then
    verify(userMgmtRestClient, times(1)).authorise(anyString(), anyString(), any());
}
 
Example 9
Source File: HttpRequestContextIntegrationFilter.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a new security context, continues the filter chain,
 * then clears the context by generating another new one.
 *
 * @param request the servlet request
 * @param response the servlet response
 * @param chain the filter chain
 * @throws IOException if an I/O error occurs
 * @throws ServletException if any other error occurs
 */
public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain)
    throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        // ensure that filter is applied only once per request
        chain.doFilter(request, response);
        return;
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    if (LOG.isDebugEnabled()) {
        LOG.debug("New SecurityContext instance associated with SecurityContextHolder");
    }
    SecurityContextHolder.setContext(generateNewContext());

    try {
        chain.doFilter(request, response);
    } catch (IOException ioe) {
        throw ioe;
    } catch (ServletException se) {
        throw se;
    } finally {
        // do clean up, even if there was an exception
        SecurityContextHolder.clearContext();
        if (LOG.isDebugEnabled()) {
            LOG.debug("SecurityContextHolder refreshed, as request processing completed");
        }
    }
}
 
Example 10
Source File: SecurityControllerTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Test(expected=AccessDeniedException.class)
public void testWrongUserEvents() throws Exception {
       Authentication auth = new UsernamePasswordAuthenticationToken("[email protected]", "user2");
       SecurityContext securityContext = SecurityContextHolder.getContext();
       securityContext.setAuthentication(auth);

       calendarService.findForUser(0);
       SecurityContextHolder.clearContext();
}
 
Example 11
Source File: PortalAuthenticationServiceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(HttpSession session) {
    if (session != null) {
        session.invalidate();
    }
    SecurityContextHolder.clearContext(); //invalidate webportal security context
    App.getInstance().getConnection().logout(); //invalidate webtier session
}
 
Example 12
Source File: LogoutSuccessHandler.java    From personal_book_library_web_project with MIT License 5 votes vote down vote up
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
  
    //String refererUrl = request.getHeader("Referer");
    SecurityContextHolder.clearContext();
    super.onLogoutSuccess(request, response, authentication);
}
 
Example 13
Source File: StaffToTeacherValidatorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
    repo.deleteAll("educationOrganization", null);
    repo.deleteAll("staff", null);
    repo.deleteAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, new NeutralQuery());

    SecurityContextHolder.clearContext();
}
 
Example 14
Source File: JwtSsoBasedAuthenticationFilter.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected void executeFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } finally {
        SecurityContextHolder.clearContext();
    }
}
 
Example 15
Source File: ExceptionTranslatorTest.java    From flair-registry with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    SecurityContextHolder.clearContext();
    AccountResource control = new AccountResource();
    this.mock = MockMvcBuilders.standaloneSetup(control)
        .setControllerAdvice(new ExceptionTranslator())
        .build();
}
 
Example 16
Source File: ObjectBundleServiceUserTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testUpdateUserWithNoAccessUserRole()
    throws IOException
{
    createUserAndInjectSecurityContext( true );

    Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata(
        new ClassPathResource( "dxf2/user_userrole.json" ).getInputStream(), RenderFormat.JSON );

    ObjectBundleParams params = new ObjectBundleParams();
    params.setObjectBundleMode( ObjectBundleMode.COMMIT );
    params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
    params.setObjects( metadata );

    ObjectBundle bundle = objectBundleService.create( params );

    objectBundleService.commit( bundle );

    User userB = manager.get( User.class, "MwhEJUnTHkn" );
    User userA = manager.get( User.class, "sPWjoHSY03y" );

    assertEquals( 2, userA.getUserCredentials().getUserAuthorityGroups().size() );
    assertEquals( 2, userB.getUserCredentials().getUserAuthorityGroups().size() );

    UserAuthorityGroup userManagerRole = manager.get( UserAuthorityGroup.class, "xJZBzAHI88H" );
    assertNotNull(  userManagerRole );
    userManagerRole.getUserAccesses().clear();
    userManagerRole.getUserAccesses().add( new UserAccess( userB, "rw------" ) );
    userManagerRole.setPublicAccess( "--------" );
    userManagerRole.setUser( userB );
    manager.update( userManagerRole );

    SecurityContextHolder.clearContext();
    userA.getUserCredentials().setPassword( "passwordUserA" );
    manager.update( userA );
    injectSecurityContext( userA );

   metadata = renderService.fromMetadata(
        new ClassPathResource( "dxf2/user_userrole_update.json" ).getInputStream(), RenderFormat.JSON );

    params = new ObjectBundleParams();
    params.setObjectBundleMode( ObjectBundleMode.COMMIT );
    params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
    params.setObjects( metadata );

    bundle = objectBundleService.create( params );
    objectBundleService.commit( bundle );

    assertEquals( 2, userA.getUserCredentials().getUserAuthorityGroups().size() );
    assertEquals( 2, userB.getUserCredentials().getUserAuthorityGroups().size() );

}
 
Example 17
Source File: DefaultSelectorDocumentTest.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    SecurityContextHolder.clearContext();
}
 
Example 18
Source File: AuthenticationServiceDefault.java    From restful-spring-security with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void logout(String token) {
	UserDetails logoutUser = tokenManager.removeToken(token);
	System.out.println(" *** AuthenticationServiceImpl.logout: " + logoutUser);
	SecurityContextHolder.clearContext();
}
 
Example 19
Source File: BaseJavaDelegate.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * This is what Activiti will call to execute this task. Sub-classes should override the executeImpl method to supply the actual implementation.
 *
 * @param execution the execution information.
 *
 * @throws Exception if any errors were encountered.
 */
@Override
public final void execute(DelegateExecution execution) throws Exception
{
    long taskBeginTimeMillis = 0;
    boolean taskSuccessFlag = false;
    try
    {
        // Need to clear the security context here since the current thread may have been reused,
        // which may might have left over its security context. If we do not clear the security
        // context, any subsequent calls may be restricted by the permissions given
        // to the previous thread's security context.
        SecurityContextHolder.clearContext();

        // Check if method is not allowed.
        configurationDaoHelper.checkNotAllowedMethod(this.getClass().getCanonicalName());

        // Set the security context per last updater of the current process instance's job definition.
        ApplicationUser applicationUser = getApplicationUser(execution);
        setSecurityContext(applicationUser);

        // Set the MDC property for the Activiti process instance ID and user ID.
        MDC.put(ACTIVITI_PROCESS_INSTANCE_ID_KEY, "activitiProcessInstanceId=" + execution.getProcessInstanceId());
        MDC.put(USER_ID_KEY, "userId=" + (applicationUser.getUserId() == null ? "" : applicationUser.getUserId()));

        // Log all input variables from the execution (before the execution starts).
        logInputParameters(execution);

        // Set the task begin time
        taskBeginTimeMillis = System.currentTimeMillis();

        // Perform the execution implementation handled in the sub-class.
        executeImpl(execution);

        // Set a success status as a workflow variable.
        activitiRuntimeHelper.setTaskSuccessInWorkflow(execution);

        // Set the flag to true since there is no exception thrown
        taskSuccessFlag = true;
    }
    catch (Exception ex)
    {
        handleException(execution, ex);
    }
    finally
    {
        // Log the task execution time
        logTaskExecutionTime(taskBeginTimeMillis, taskSuccessFlag);

        // Remove the MDC property to ensure they don't accidentally get used by anybody else.
        MDC.remove(ACTIVITI_PROCESS_INSTANCE_ID_KEY);
        MDC.remove(USER_ID_KEY);

        // Clear up the security context.
        SecurityContextHolder.clearContext();
    }
}
 
Example 20
Source File: EntityServiceLayerTest.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    SecurityContextHolder.clearContext();
}