Java Code Examples for org.springframework.security.core.context.SecurityContext

The following examples show how to use org.springframework.security.core.context.SecurityContext. These examples are extracted from open source projects. 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 Project: flair-registry   Source File: AccountResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExistingAccount() throws Exception {

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

    Collection authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));
    Mockito.when(authentication.getAuthorities()).thenReturn(authorities);

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example 2
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example 3
Source Project: java-microservices-examples   Source File: SecurityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example 4
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example 5
Source Project: java-microservices-examples   Source File: SecurityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example 6
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example 7
Source Project: sdn-rx   Source File: Neo4jConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This bean is only active in profile {@literal "selection-by-user"}. The {@link DatabaseSelectionProvider} created here
 * uses Springs security context to retrieve the authenticated principal and extracts the username. Thus all requests
 * will use a different database, depending on the user being logged into the application.
 *
 * @return A database name provider.
 */
@Profile("selection-by-user")
// tag::faq.multidatabase[]
@Bean
DatabaseSelectionProvider databaseSelectionProvider() {

	return () -> Optional.ofNullable(SecurityContextHolder.getContext())
		.map(SecurityContext::getAuthentication)
		.filter(Authentication::isAuthenticated)
		.map(Authentication::getPrincipal)
		.map(User.class::cast)
		.map(User::getUsername)
		.map(DatabaseSelection::byName)
		.orElseGet(DatabaseSelection::undecided);
}
 
Example 8
Source Project: cubeai   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    Optional<String> login = SecurityUtils.getCurrentUserLogin();
    assertThat(login).contains("admin");
}
 
Example 9
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
                                        Authentication authResult) throws IOException, ServletException {
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authResult);
    SecurityContextHolder.setContext(context);
    chain.doFilter(request, response);
}
 
Example 10
Source Project: flair-registry   Source File: ExceptionTranslatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void processParameterizedValidationErrorTest() throws Exception {
    // These lines will throw the wanted exception
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenThrow(new CustomParameterizedException(null));
    SecurityContextHolder.setContext(securityContext);

    MvcResult res = mock.perform(get("/api/account"))
        .andExpect(status().isBadRequest())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(CustomParameterizedException.class));
}
 
Example 11
Source Project: flair-registry   Source File: ExceptionTranslatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void processAccessDeniedExceptionTest() throws Exception {
    // These lines will throw the wanted exception
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenThrow(new AccessDeniedException(null));
    SecurityContextHolder.setContext(securityContext);

    MvcResult res = mock.perform(get("/api/account"))
        .andExpect(status().isForbidden())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(AccessDeniedException.class));
}
 
Example 12
Source Project: flair-registry   Source File: ExceptionTranslatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void processRuntimeExceptionTest() throws Exception {

    // These lines will throw the wanted exception
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenThrow(new RuntimeException());
    SecurityContextHolder.setContext(securityContext);

    MvcResult res = mock.perform(get("/api/account"))
        .andExpect(status().isInternalServerError())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(RuntimeException.class));
}
 
Example 13
Source Project: xmall   Source File: UmsMemberServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public UmsMember getCurrentMember() {
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
    return memberDetails.getUmsMember();
}
 
Example 14
private void setupUser(String... privs) {
  SecurityContext securityContext = SecurityContextHolder.getContext();
  List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  for (String priv : privs) {
    authorities.add(new SimpleGrantedAuthority(priv));
  }
  UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("user", "password", authorities);
  securityContext.setAuthentication(authenticationToken);
}
 
Example 15
Source Project: cubeai   Source File: UserFeignClientInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example 16
Source Project: flair-engine   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
Example 17
Source Project: flair-engine   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user
 */
public static String getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null && authentication.getCredentials() instanceof String) {
        return (String) authentication.getCredentials();
    }
    return null;
}
 
Example 18
Source Project: flair-engine   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise
 */
public static boolean isAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        return authentication.getAuthorities().stream()
            .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS));
    }
    return false;
}
 
Example 19
Source Project: flair-engine   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If the current user has a specific authority (security role).
 * <p>
 * The name of this method comes from the isUserInRole() method in the Servlet API
 *
 * @param authority the authority to check
 * @return true if the current user has the authority, false otherwise
 */
public static boolean isCurrentUserInRole(String authority) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        return authentication.getAuthorities().stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority));
    }
    return false;
}
 
Example 20
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    String login = SecurityUtils.getCurrentUserLogin();
    assertThat(login).isEqualTo("admin");
}
 
Example 21
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
    SecurityContextHolder.setContext(securityContext);
    String jwt = SecurityUtils.getCurrentUserJWT();
    assertThat(jwt).isEqualTo("token");
}
 
Example 22
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isTrue();
}
 
Example 23
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
 
Example 24
Source Project: cubeai   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise
 */
public static boolean isAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> authentication.getAuthorities().stream()
            .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)))
        .orElse(false);
}
 
Example 25
@Bean
AuditorAware<Author> auditorAware(AuthorRepository repo) {
	// Lookup Author instance corresponding to logged in user
	return () -> Optional.ofNullable(SecurityContextHolder.getContext())
			.map(SecurityContext::getAuthentication)
			.filter(Authentication::isAuthenticated)
			.map(Authentication::getName)
			.flatMap(repo::findByName);
}
 
Example 26
Source Project: alchemy   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example 27
Source Project: alchemy   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user.
 */
public static Optional<String> getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .filter(authentication -> authentication.getCredentials() instanceof String)
        .map(authentication -> (String) authentication.getCredentials());
}
 
Example 28
Source Project: alchemy   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise.
 */
public static boolean isAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> authentication.getAuthorities().stream()
            .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)))
        .orElse(false);
}
 
Example 29
Source Project: alchemy   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    Optional<String> login = SecurityUtils.getCurrentUserLogin();
    assertThat(login).contains("admin");
}
 
Example 30
Source Project: alchemy   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
    SecurityContextHolder.setContext(securityContext);
    Optional<String> jwt = SecurityUtils.getCurrentUserJWT();
    assertThat(jwt).contains("token");
}