Example usage for org.springframework.security.core.context SecurityContextHolder getContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder getContext

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder getContext.

Prototype

public static SecurityContext getContext() 

Source Link

Document

Obtain the current SecurityContext.

Usage

From source file:ro.allevo.fintpws.security.RolesUtils.java

public static boolean hasUserOrAdministratorRole() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserEntity loggedUser = (UserEntity) authentication.getPrincipal();
    List<RoleEntity> roles = (List<RoleEntity>) loggedUser.getAuthorities();
    for (int roleIndex = 0; roleIndex < roles.size(); roleIndex++) {
        if (roles.get(roleIndex).getAuthority().equals("Administrator")
                || roles.get(roleIndex).getAuthority().equals("Basic user")) {
            return true;
        }/*from w  w  w.j a va 2s .  c o m*/

    }
    return false;
}

From source file:scratch.cucumber.example.security.spring.StatelessAuthenticationFilterTest.java

@Test
public void Can_authenticate_request() throws IOException, ServletException {

    @SuppressWarnings("unchecked")
    final HttpServletRequestBinder<Authentication> authenticationFactory = mock(HttpServletRequestBinder.class);
    final SecurityContextHolder contextHolder = mock(SecurityContextHolder.class);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    final ServletResponse response = mock(ServletResponse.class);
    final FilterChain filterChain = mock(FilterChain.class);

    final Authentication authentication = mock(Authentication.class);
    final SecurityContext securityContext = mock(SecurityContext.class);

    // Given/*ww w. ja va 2  s . c o  m*/
    given(authenticationFactory.retrieve(request)).willReturn(authentication);
    given(contextHolder.getContext()).willReturn(securityContext);

    // When
    new StatelessAuthenticationFilter(authenticationFactory, contextHolder).doFilter(request, response,
            filterChain);

    // Then
    final InOrder order = inOrder(securityContext, filterChain);
    order.verify(securityContext).setAuthentication(authentication);
    order.verify(filterChain).doFilter(request, response);
}

From source file:com.changeme.security.SecurityUtils.java

/**
 * Configures the Spring Security {@link SecurityContext} to be authenticated as the user with the given username and
 * password as well as the given granted authorities.
 * /*ww w. j  a v a2s. c o m*/
 * @param username must not be {@literal null} or empty.
 * @param password must not be {@literal null} or empty.
 * @param roles
 */
public static void runAs(String username, String password, String... roles) {

    Assert.notNull(username, "Username must not be null!");
    Assert.notNull(password, "Password must not be null!");

    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username,
            password, AuthorityUtils.createAuthorityList(roles)));
}

From source file:com.mothsoft.alexis.security.CurrentUserUtil.java

public static boolean isAuthenticated() {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName());
}

From source file:ru.mystamps.web.support.spring.security.SecurityContextUtils.java

/**
 * @author Sergey Chechenev//  w  w  w .  j  a va  2s.  c o m
 * @author Slava Semushin
 */
public static Integer getUserId() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
            .map(Authentication::getPrincipal).filter(CustomUserDetails.class::isInstance)
            .map(CustomUserDetails.class::cast).map(CustomUserDetails::getUserId).orElse(null);
}

From source file:org.mashupmedia.util.AdminHelper.java

public static User getLoggedInUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return null;
    }//from   w  ww .ja v  a  2  s  .c o  m

    Object principal = authentication.getPrincipal();
    if (principal == null) {
        return null;
    }

    if (principal instanceof User) {
        User user = (User) principal;
        return user;
    }

    return null;
}

From source file:uk.ac.ebi.emma.controller.GeneManagementDetailControllerTest.java

@BeforeClass
public static void setUpClass() {
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("test", ""));
}

From source file:bookpub.security.SecurityUtils.java

/**
 * <security:http> adds an AnonymousAuthenticationFilter which creates an
 * Authentication token for anonymous users. The problem is that
 * Authentication.isAuthenticated() will then return true even for anonymous
 * users, so we have to use a AuthenticationTrustResolver to check for
 * anonymous/authenticated.// w  w  w .ja  va  2  s.  c o m
 */
public static boolean isAnonymous() {
    return authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication());
}

From source file:org.opentides.util.SecurityUtil.java

/**
 * Static helper to retrieve currently logged user.
 * @return/*  w w  w .j a v a  2s  .c o  m*/
 */
public static SessionUser getSessionUser() {
    try {
        Object userObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userObj instanceof SessionUser)
            return ((SessionUser) userObj);
    } catch (NullPointerException npe) {
        _log.warn("No Security Context Found!");
    } catch (Exception e) {
        _log.error(e.getMessage());
    }
    return null;
}

From source file:egovframework.let.utl.fcc.service.EgovAuthUtil.java

/**
 * @return true if the user has one of the specified roles.
 *//*from w ww  . j av  a  2s  .  com*/
public static boolean hasRole(String[] roles) {
    boolean result = false;
    for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
        String userRole = authority.getAuthority();
        for (String role : roles) {
            if (role.equals(userRole)) {
                result = true;
                break;
            }
        }

        if (result) {
            break;
        }
    }

    return result;
}