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

The following examples show how to use org.springframework.security.core.context.SecurityContextHolder#getContext() . 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: NiFiUserUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the current NiFiUser or null if the current user is not a NiFiUser.
 *
 * @return user
 */
public static NiFiUser getNiFiUser() {
    NiFiUser user = null;

    // obtain the principal in the current authentication
    final SecurityContext context = SecurityContextHolder.getContext();
    final Authentication authentication = context.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof NiFiUserDetails) {
            user = ((NiFiUserDetails) principal).getNiFiUser();
        }
    }

    return user;
}
 
Example 2
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }

    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();
    if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
Example 3
Source File: SecurityService.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get currently connected User.
 * 
 * @return Current User.
 */
public User getCurrentUser ()
{
   SecurityContext context = SecurityContextHolder.getContext ();

   if (context == null)
   {
      LOGGER.error("No security context");
      return null;
   }

   Authentication auth =
      SecurityContextHolder.getContext ().getAuthentication ();
   if (auth == null)
   {
      LOGGER.error("No auth in security context");
      return null;
   }
   Object principal = auth.getPrincipal ();
   if (principal instanceof User)
   {
      return (User) principal;
   }
   LOGGER.debug("Principal class : " + principal.getClass ());
   return null;
}
 
Example 4
Source File: PermissionCheckingDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testAggregateSystemUser() {
  SecurityContext originalSecurityContext = SecurityContextHolder.getContext();
  try {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(
        new UsernamePasswordAuthenticationToken(
            "principal", "credentials", singleton(new SimpleGrantedAuthority("ROLE_SYSTEM"))));
    SecurityContextHolder.setContext(securityContext);

    AggregateQuery aggregateQuery = mock(AggregateQuery.class);
    permissionCheckingDecorator.aggregate(aggregateQuery);
    verify(delegateRepository).aggregate(aggregateQuery);
  } finally {
    SecurityContextHolder.setContext(originalSecurityContext);
  }
}
 
Example 5
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();        if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
Example 6
Source File: SecurityUtils.java    From tutorials with MIT License 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</p>
 *
 * @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 7
Source File: RunAsSystemAspect.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static <T, X extends Throwable> T runAsSystem(RunnableAsSystem<T, X> runnable) throws X {
  // Remember the original context
  SecurityContext origCtx = SecurityContextHolder.getContext();
  try {
    // Set a SystemSecurityToken
    SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
    SecurityContextHolder.getContext().setAuthentication(SystemSecurityToken.getInstance());
    return runnable.run();
  } finally {
    // Set the original context back when method is finished
    SecurityContextHolder.setContext(origCtx);
  }
}
 
Example 8
Source File: SecurityUtils.java    From scava with Eclipse Public 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 9
Source File: SecurityUtil.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public static String getEdOrg() {
    SLIPrincipal principal = null;
    SecurityContext context = SecurityContextHolder.getContext();
    if (context.getAuthentication() != null) {
        principal = (SLIPrincipal) context.getAuthentication().getPrincipal();
        return principal.getEdOrg();
    }
    return null;
}
 
Example 10
Source File: SecurityUtils.java    From cubeai with 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 11
Source File: SecurityUtils.java    From tutorials with MIT License 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</p>
 *
 * @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 12
Source File: SecurityUtils.java    From angularjs-springboot-bookstore with MIT License 5 votes vote down vote up
/**
 * If the current user has a specific security role.
 */
public static boolean isUserInRole(String role) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if(authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(role));
        }
    }
    return false;
}
 
Example 13
Source File: UserContextUtil.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Allow role in security context.
 *
 * @param role
 *            the role
 * @return true, if successful
 */
public static boolean allowRoleInSecurityContext(final String role) {
	boolean result = false;
	final SecurityContext context = SecurityContextHolder.getContext();
	if (context != null && context.getAuthentication() != null) {
		final Collection<? extends GrantedAuthority> authorities = context.getAuthentication().getAuthorities();

		for (final GrantedAuthority grantedAuthority : authorities) {
			if (role.equalsIgnoreCase(grantedAuthority.getAuthority())) {
				result = true;
			}
		}
	}
	return result;
}
 
Example 14
Source File: CosmoSecurityManagerImpl.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Authenticate the given Cosmo credentials and register a <code>CosmoSecurityContext</code> for them. This method
 * is used when Cosmo components need to programatically log in a user rather than relying on a security context
 * already being in place.
 */
public CosmoSecurityContext initiateSecurityContext(String username, String password)
        throws CosmoSecurityException {
    try {
        UsernamePasswordAuthenticationToken credentials = new UsernamePasswordAuthenticationToken(username,
                password);
        Authentication authentication = authenticationManager.authenticate(credentials);
        SecurityContext sc = SecurityContextHolder.getContext();
        sc.setAuthentication(authentication);
        return createSecurityContext(authentication);
    } catch (AuthenticationException e) {
        throw new CosmoSecurityException("can't establish security context", e);
    }
}
 
Example 15
Source File: SecurityUtils.java    From jhipster-microservices-example with 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 16
Source File: UserContextUtil.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the user id from security context.
 *
 * @return the user id from security context
 */
public static String getUserIdFromSecurityContext() {
	final SecurityContext context = SecurityContextHolder.getContext();
	if (context != null) {
		final Authentication authentication = context.getAuthentication();
		if (authentication != null) {
			return authentication.getPrincipal().toString();
		}
	}
	return null;
}
 
Example 17
Source File: SecurityUtils.java    From jhipster-ribbon-hystrix with GNU General Public License v3.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</p>
 *
 * @param authority the authorithy 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) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority));
        }
    }
    return false;
}
 
Example 18
Source File: UserHolder.java    From spring-security with Apache License 2.0 4 votes vote down vote up
public static int getUserId(){
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    TUser user = (TUser) auth.getPrincipal();
    return user.getId();
}
 
Example 19
Source File: SecurityUtils.java    From 21-points with Apache License 2.0 3 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();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> authentication.getAuthorities().stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
        .orElse(false);
}
 
Example 20
Source File: AccessTokenUtils.java    From spring-boot with Apache License 2.0 3 votes vote down vote up
public static Optional<String> getUserNameFromSecurityContext() {

        SecurityContext securityContext = SecurityContextHolder.getContext();

        Authentication authentication = securityContext.getAuthentication();
        if (authentication instanceof OAuth2Authentication) {

            return Optional.ofNullable(authentication.getName());

        } else {

            return Optional.empty();
        }

    }