Java Code Examples for org.springframework.security.core.authority.AuthorityUtils#NO_AUTHORITIES

The following examples show how to use org.springframework.security.core.authority.AuthorityUtils#NO_AUTHORITIES . 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: RepositoryAuthenticationProvider.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private UserDetails mapUserEntityToUserDetails(UserEntity userEntity) {
	List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
	if (userEntity.getRoles() != null && userEntity.getRoles().size() > 0) {

		authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
				userEntity.getRoles().stream().map(r -> r.getScope().name()+':'+r.getName()).collect(Collectors.joining(","))
		);
	}

	io.gravitee.rest.api.idp.api.authentication.UserDetails userDetails = new io.gravitee.rest.api.idp.api.authentication.UserDetails(
			userEntity.getId(), userEntity.getPassword(), authorities);

	userDetails.setFirstname(userEntity.getFirstname());
	userDetails.setLastname(userEntity.getLastname());
	userDetails.setEmail(userEntity.getEmail());
	userDetails.setSource(RepositoryIdentityProvider.PROVIDER_TYPE);
	userDetails.setSourceId(userEntity.getSourceId());

	return userDetails;
}
 
Example 2
Source File: CachedRoleHierarchyImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getReachableGrantedAuthorities(
    Collection<? extends GrantedAuthority> authorities) {
  Collection<? extends GrantedAuthority> reachableGrantedAuthorities;

  if (authorities == null || authorities.isEmpty()) {
    reachableGrantedAuthorities = AuthorityUtils.NO_AUTHORITIES;
  } else {
    Boolean isCacheDirty = cacheDirty.get();
    if (isCacheDirty == null || !isCacheDirty) {
      reachableGrantedAuthorities = getCachedReachableAuthorities(authorities);
    } else {
      reachableGrantedAuthorities = getPersistedReachableGrantedAuthorities(authorities);
    }
  }

  return reachableGrantedAuthorities;
}
 
Example 3
Source File: FebsUserDetailServiceImpl.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
    SystemUser systemUser = userManager.findByName(username);
    if (systemUser != null) {
        String permissions = userManager.findUserPermissions(systemUser.getUsername());
        boolean notLocked = false;
        if (StringUtils.equals(SystemUser.STATUS_VALID, systemUser.getStatus())) {
            notLocked = true;
        }
        String password = systemUser.getPassword();
        String loginType = (String) httpServletRequest.getAttribute(ParamsConstant.LOGIN_TYPE);
        if (StringUtils.equals(loginType, SocialConstant.SOCIAL_LOGIN)) {
            password = passwordEncoder.encode(SocialConstant.SOCIAL_LOGIN_PASSWORD);
        }

        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.NO_AUTHORITIES;
        if (StringUtils.isNotBlank(permissions)) {
            grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(permissions);
        }
        FebsAuthUser authUser = new FebsAuthUser(systemUser.getUsername(), password, true, true, true, notLocked,
                grantedAuthorities);

        BeanUtils.copyProperties(systemUser, authUser);
        return authUser;
    } else {
        throw new UsernameNotFoundException("");
    }
}
 
Example 4
Source File: OpenUserConverter.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 获取权限
 *
 * @param map
 * @return
 */
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
    if (!map.containsKey(AUTHORITIES)) {
        return AuthorityUtils.NO_AUTHORITIES;
    }
    Object authorities = map.get(AUTHORITIES);
    if (authorities instanceof String) {
        return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
    }
    if (authorities instanceof Collection) {
        return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                .collectionToCommaDelimitedString((Collection<?>) authorities));
    }
    throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
 
Example 5
Source File: CasUserDetailService.java    From cymbal with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
    String userName = token.getName();
    if (userRoleProcessService.isAdmin(userName)) {
        return new User(userName, Constant.Strings.EMPTY,
                AuthorityUtils.createAuthorityList(UserRole.ADMIN.getValue()));
    } else {
        return new User(userName, Constant.Strings.EMPTY, AuthorityUtils.NO_AUTHORITIES);
    }
}
 
Example 6
Source File: DbUserDetailService.java    From cymbal with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    User user = userEntityService.getByUserName(userName);
    if (Objects.isNull(user)) {
        throw new UsernameNotFoundException(String.format("Can not find a user with name '%s'.", userName));
    }
    if (userRoleProcessService.isAdmin(userName)) {
        return new org.springframework.security.core.userdetails.User(userName, user.getPassword(),
                AuthorityUtils.createAuthorityList(UserRole.ADMIN.getValue()));
    } else {
        return new org.springframework.security.core.userdetails.User(userName, user.getPassword(),
                AuthorityUtils.NO_AUTHORITIES);
    }
}
 
Example 7
Source File: SocialAuthenticationFilter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    // get oauth2 provider
    String providerId = request.getParameter(PROVIDER_PARAMETER);
    AuthenticationProvider authenticationProvider = identityProviderManager.get(providerId);

    if (authenticationProvider == null) {
        throw new ProviderNotFoundException("Social Provider " + providerId + " not found");
    }

    SimpleAuthenticationContext authenticationContext = new SimpleAuthenticationContext(new JettyHttpServerRequest(request));
    authenticationContext.set(REDIRECT_URI, buildRedirectUri(request));
    EndUserAuthentication provAuthentication = new EndUserAuthentication("__social__", "__social__", authenticationContext);

    try {
        User user = authenticationProvider.loadUserByUsername(provAuthentication).blockingGet();
        if (user == null) {
            logger.error("User is null, fail to authenticate user");
            throw new BadCredentialsException("User is null after authentication process");
        }

        // set user identity provider source
        Map<String, String> details = new LinkedHashMap<>();
        details.put(SOURCE, providerId);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, provAuthentication.getCredentials(), AuthorityUtils.NO_AUTHORITIES);
        usernamePasswordAuthenticationToken.setDetails(details);
        return usernamePasswordAuthenticationToken;
    } catch (Exception ex) {
        logger.error("Unable to authenticate with oauth2 provider {}", providerId, ex);
        throw new BadCredentialsException(ex.getMessage(), ex);
    }
}
 
Example 8
Source File: WebAuthnProcessingFilterTest.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Test
public void constructor_test() {
    ServerPropertyProvider serverPropertyProvider = mock(ServerPropertyProvider.class);
    WebAuthnProcessingFilter webAuthnProcessingFilter = new WebAuthnProcessingFilter(AuthorityUtils.NO_AUTHORITIES, serverPropertyProvider);
    Assertions.assertThat(webAuthnProcessingFilter.getServerPropertyProvider()).isEqualTo(serverPropertyProvider);
}
 
Example 9
Source File: JwtAuthenticationToken.java    From jersey-jwt-springsecurity with MIT License 4 votes vote down vote up
/**
 * Creates a {@link JwtAuthenticationToken} instance for an unauthenticated token.
 *
 * @param authenticationToken
 */
public JwtAuthenticationToken(String authenticationToken) {
    super(AuthorityUtils.NO_AUTHORITIES);
    this.authenticationToken = authenticationToken;
    this.setAuthenticated(false);
}
 
Example 10
Source File: JWTAuthenticationFilter.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    String authToken;

    // first check Authorization request header
    final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorization != null && authorization.startsWith("Bearer ")) {
        authToken = authorization.substring(7);
    } else {
        // if no authorization header found, check authorization cookie
        final Optional<Cookie> optionalStringToken;

        if (request.getCookies() == null) {
            optionalStringToken = Optional.empty();
        } else {
            optionalStringToken = Arrays.stream(request.getCookies())
                    .filter(cookie -> authCookieName.equals(cookie.getName()))
                    .findAny();
        }

        if (!optionalStringToken.isPresent() || !optionalStringToken.get().getValue().startsWith("Bearer ")) {
            throw new BadCredentialsException("No JWT token found");
        }
        authToken = optionalStringToken.get().getValue().substring(7);
    }

    try {
        JwtParser jwtParser = Jwts.parser().setSigningKey(key);
        Map<String, Object> claims = new HashMap<>(jwtParser.parseClaimsJws(authToken).getBody());
        claims.put(Claims.ip_address, remoteAddress(request));
        claims.put(Claims.user_agent, userAgent(request));
        DefaultUser user = new DefaultUser((String) claims.get(StandardClaims.PREFERRED_USERNAME));
        user.setId((String) claims.get(StandardClaims.SUB));
        user.setRoles(user.getRoles() != null ? user.getRoles() : (List<String>) claims.get(CustomClaims.ROLES));
        user.setAdditionalInformation(claims);

        // check for roles
        List<GrantedAuthority> authorities;
        if (user.getRoles() != null) {
            authorities = user.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        } else {
            authorities = AuthorityUtils.NO_AUTHORITIES;
        }
        return new UsernamePasswordAuthenticationToken(user, null, authorities);
    } catch (Exception ex) {
        removeJWTAuthenticationCookie(response);
        throw new BadCredentialsException("Error occurs while attempting authentication", ex);
    }
}