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

The following examples show how to use org.springframework.security.core.authority.AuthorityUtils. 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: SpringAll   Source File: UserDetailService.java    License: MIT License 8 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 模拟一个用户,替代数据库获取逻辑
    MyUser user = new MyUser();
    user.setUserName(username);
    user.setPassword(this.passwordEncoder.encode("123456"));
    // 输出加密后的密码
    System.out.println(user.getPassword());

    List<GrantedAuthority> authorities = new ArrayList<>();
    if (StringUtils.equalsIgnoreCase("mrbird", username)) {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
    } else {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test");
    }
    return new User(username, user.getPassword(), user.isEnabled(),
            user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), authorities);
}
 
Example 2
@Bean
UserDetailsService userDetailsService() {
    return username -> {
        LOGGER.debug(String.format("Looking for user [%s]", username));
        Account account = accountRepository.findByUsername(username);
        if (account != null) {
            LOGGER.info(String.format("Found user [%s]", username));
            return new User(account.getUsername(), account.getPassword(),
                    true, true, true, true,
                    AuthorityUtils.createAuthorityList("USER"));
        } else {
            LOGGER.info(String.format("Couldn't find user [%s]", username));
            throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username));
        }
    };
}
 
Example 3
Source Project: elucidate-server   Source File: JwtUserAuthenticationConverter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication extractAuthentication(Map<String, ?> details) {
    return uidProperties.stream()
        .filter(details::containsKey)
        .map(prop -> (String) details.get(prop))
        .findFirst()
        .map(uid -> {
            UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
            Collection<String> roles = (Collection<String>) details.get(AUTHORITIES);

            if (roles == null) {
                roles = Collections.emptyList();
            }

            List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0]));
            Authentication auth = new UsernamePasswordAuthenticationToken(
                securityDetails,
                "N/A",
                authorities
            );

            return auth;
        })
        .orElse(null);
}
 
Example 4
Source Project: WeEvent   Source File: AccountDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    log.info("username: {}", username);
    AccountEntity accountEntity = null;
    try {
        accountEntity = accountService.queryByUsername(username);
    } catch (Exception e) {
        throw new UsernameNotFoundException("sql execute error!");
    }
    String password = accountEntity.getPassword();

    log.info("password: {}", password);

    User user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    return user;
}
 
Example 5
Source Project: SpringAll   Source File: UserDetailService.java    License: MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 模拟一个用户,替代数据库获取逻辑
    MyUser user = new MyUser();
    user.setUserName(username);
    user.setPassword(this.passwordEncoder.encode("123456"));
    // 输出加密后的密码
    System.out.println(user.getPassword());

    List<GrantedAuthority> authorities = new ArrayList<>();
    if (StringUtils.equalsIgnoreCase("mrbird", username)) {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
    } else {
        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test");
    }
    return new User(username, user.getPassword(), user.isEnabled(),
            user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), authorities);
}
 
Example 6
Source Project: telekom-workflow-engine   Source File: WorkConsumerJobImpl.java    License: MIT License 6 votes vote down vote up
@Override
public synchronized void start(){
    isStopping.set( false );

    // number of parallel consumer threads
    int numberOfConsumerThreads = config.getNumberOfConsumerThreads();

    // spring security context for executor threads
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("workflow-engine", "[not-used]", AuthorityUtils.createAuthorityList("ROLE_WORKFLOW_ENGINE")));

    // actual executor thread pool
    ExecutorService delegateExecutorService = Executors.newFixedThreadPool( numberOfConsumerThreads, new NamedPoolThreadFactory( "consumer" ) );
    // wrapper executor service that sets the security context for each thread
    executorService = new DelegatingSecurityContextExecutorService(delegateExecutorService, securityContext);

    // start the consuming jobs
    for( int i = 0; i < numberOfConsumerThreads; i++ ){
        executorService.execute( new ConsumerRunnable() );
    }
    log.info( "Scheduled {} consumers", numberOfConsumerThreads );
}
 
Example 7
Source Project: springBoot   Source File: UserConfig.java    License: MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //查询用户
    SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData();
    //查询权限
    List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData();
    StringBuilder authoritys = new StringBuilder();
    for (int i = 0; i < sysUserAuthorityVoList.size(); i++) {
        SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i);
        authoritys.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName());
        if (i != sysUserAuthorityVoList.size() - 1) {
            authoritys.append(",");
        }
    }
    // 封装用户信息,并返回。参数分别是:用户名,密码,用户权限
    return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authoritys.toString()));
}
 
Example 8
Source Project: MaxKey   Source File: DefaultAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
	Map<String, String> parameters = new HashMap<String, String>();
	@SuppressWarnings("unchecked")
	Set<String> scope = new LinkedHashSet<String>(map.containsKey(SCOPE) ? (Collection<String>) map.get(SCOPE)
			: Collections.<String>emptySet());
	Authentication user = userTokenConverter.extractAuthentication(map);
	String clientId = (String) map.get(CLIENT_ID);
	parameters.put(CLIENT_ID, clientId);
	if (includeGrantType && map.containsKey(GRANT_TYPE)) {
		parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE));
	}
	@SuppressWarnings("unchecked")
	Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD)
			: Collections.<String>emptySet());
	
	Collection<? extends GrantedAuthority> authorities = null;
	if (user==null && map.containsKey(AUTHORITIES)) {
		@SuppressWarnings("unchecked")
		String[] roles = ((Collection<String>)map.get(AUTHORITIES)).toArray(new String[0]);
		authorities = AuthorityUtils.createAuthorityList(roles);
	}
	OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null,
			null);
	return new OAuth2Authentication(request, user);
}
 
Example 9
Source Project: base-admin   Source File: UserConfig.java    License: MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //查询用户
    SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData();
    //查询权限
    List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData();
    StringBuilder authorityList = new StringBuilder();
    for (int i = 0; i < sysUserAuthorityVoList.size(); i++) {
        SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i);
        authorityList.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName());
        if (i != sysUserAuthorityVoList.size() - 1) {
            authorityList.append(",");
        }
    }

    //查无此用户
    if(StringUtils.isEmpty(sysUserVo.getUserId())){
        sysUserVo.setLoginName("查无此用户");
        sysUserVo.setPassword("查无此用户");
    }

    // 封装用户信息,并返回。参数分别是:用户名,密码,用户权限
    return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList.toString()));
}
 
Example 10
@Override
public AuthenticatedExternalWebService authenticate(String username, String password) {
    ExternalWebServiceStub externalWebService = new ExternalWebServiceStub();

    // Do all authentication mechanisms required by external web service protocol and validated response.
    // Throw descendant of Spring AuthenticationException in case of unsucessful authentication. For example BadCredentialsException

    // ...
    // ...

    // If authentication to external service succeeded then create authenticated wrapper with proper Principal and GrantedAuthorities.
    // GrantedAuthorities may come from external service authentication or be hardcoded at our layer as they are here with ROLE_DOMAIN_USER
    AuthenticatedExternalWebService authenticatedExternalWebService = new AuthenticatedExternalWebService(new DomainUser(username), null,
            AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_DOMAIN_USER"));
    authenticatedExternalWebService.setExternalWebService(externalWebService);

    return authenticatedExternalWebService;
}
 
Example 11
@Test
void createSessionWithSecurityContextAndFindByPrincipal() {
	Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy,
			"Hazelcast runs in embedded server topology");

	HazelcastSession session = this.repository.createSession();

	String username = "saves-" + System.currentTimeMillis();
	Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
	securityContext.setAuthentication(authentication);
	session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext);

	this.repository.save(session);

	assertThat(this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
					.hasSize(1);
}
 
Example 12
Source Project: Cerberus   Source File: CerberusUserFactory.java    License: MIT License 6 votes vote down vote up
public static CerberusUser create(User user) {
  Collection<? extends GrantedAuthority> authorities;
  try {
    authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getAuthorities());
  } catch (Exception e) {
    authorities = null;
  }
  return new CerberusUser(
    user.getId(),
    user.getUsername(),
    user.getPassword(),
    user.getEmail(),
    user.getLastPasswordReset(),
    authorities
  );
}
 
Example 13
/**
 * 定义access_token内容,JWT谁都可读
 * 不应该在载荷里面加入任何敏感的数据
 */
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	LinkedHashMap<String,Object> response = new LinkedHashMap<>();
	String name = authentication.getName();
	Object principal = authentication.getPrincipal();
	UserJwt userJwt = null;
	if(principal instanceof  UserJwt){
		userJwt = (UserJwt) principal;
	}else{
		//refresh_token默认不去调用userdetailService获取用户信息,手动去调用,得到 UserJwt
		UserDetails userDetails = userDetailsService.loadUserByUsername(name);
		userJwt = (UserJwt) userDetails;
	}
	if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
		response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	}
	response.put("id", userJwt.getId());
	return response;
}
 
Example 14
@Test
@SuppressWarnings("unchecked")
void findByIndexNameAndIndexValuePrincipalIndexNameFound() {
	String principal = "username";
	Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	List<Session> saved = new ArrayList<>(2);
	Session saved1 = this.repository.createSession();
	saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
	saved.add(saved1);
	Session saved2 = this.repository.createSession();
	saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
	saved.add(saved2);
	given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class))).willReturn(saved);

	Map<String, JdbcSession> sessions = this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);

	assertThat(sessions).hasSize(2);
	verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class));
}
 
Example 15
Source Project: syndesis   Source File: SecurityConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception {
    RequestHeaderAuthenticationFilter f = new RequestHeaderAuthenticationFilter();
    f.setPrincipalRequestHeader("X-Forwarded-User");
    f.setCredentialsRequestHeader("X-Forwarded-Access-Token");
    f.setAuthenticationManager(authenticationManager());
    f.setAuthenticationDetailsSource(
        (AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>)
            (request) ->new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
                request,
                AuthorityUtils.createAuthorityList("ROLE_AUTHENTICATED")
            )
    );
    f.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
    f.setExceptionIfHeaderMissing(false);
    return f;
}
 
Example 16
/**
 * Mock OAuth2Request
 * 
 * @param withMockOAuth2Token
 * @return
 */
private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) {
	String clientId = withMockOAuth2Token.clientId();
	Map<String, String> requestParameters = Collections.emptyMap();
	boolean approved = true;
	String redirectUrl = withMockOAuth2Token.redirectUrl();
	Set<String> responseTypes = Collections.emptySet();
	Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes()));
	Set<String> resourceIds = Collections.emptySet();
	Map<String, Serializable> extensionProperties = Collections.emptyMap();
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes,
			resourceIds, redirectUrl, responseTypes, extensionProperties);

	return oAuth2Request;
}
 
Example 17
Source Project: hauth-java   Source File: JwtService.java    License: MIT License 6 votes vote down vote up
public static Authentication getAuthentication(HttpServletRequest request) {

        // 从Header中拿到token
        String token = request.getHeader(HEADER_STRING);
        if (token == null) {
            token = getTokenFromCookis(request);
        }

        if (token != null && !token.isEmpty()) {
            // 解析 Token
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            // 获取用户名
            String user = claims.get("UserId").toString();

            // 获取权限(角色)
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));

            // 返回验证令牌
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
        }
        return null;
    }
 
Example 18
public UserDetails loadUserByUsername(String username)
		throws UsernameNotFoundException {
	// TODO Auto-generated method stub
	
	User user = null;
	try {
		user = userMapper.getUserByName(username);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	if(user == null)
		throw new UsernameNotFoundException("user not found!");
	//roles=角色代码
	List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles());
	userInfo = new UserInfo(username,user.getPassword(),user.isEnabled(),true,true,true,authorities);
	userInfo.setUserid(user.getUserId());
	userInfo.setRolesName(user.getRoles());
	userInfo.setTrueName(user.getTrueName());
	userInfo.setEmail(user.getEmail());
	userInfo.setPhoneNum(user.getPhoneNum());
	userInfo.setNationalId(user.getNationalId());
	userInfo.setDepId(user.getDepId());
	return userInfo;
}
 
Example 19
Source Project: blackduck-alert   Source File: AuthenticationHandler.java    License: Apache License 2.0 6 votes vote down vote up
private ObjectPostProcessor<AffirmativeBased> createRoleProcessor() {
    return new ObjectPostProcessor<>() {
        @Override
        public AffirmativeBased postProcess(AffirmativeBased affirmativeBased) {
            WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
            DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
            expressionHandler.setRoleHierarchy(authorities -> {
                String[] allAlertRoles = retrieveAllowedRoles();
                return AuthorityUtils.createAuthorityList(allAlertRoles);
            });
            webExpressionVoter.setExpressionHandler(expressionHandler);
            affirmativeBased.getDecisionVoters().add(webExpressionVoter);
            return affirmativeBased;
        }
    };
}
 
Example 20
Source Project: zhcet-web   Source File: RoleWiseSuccessHandler.java    License: Apache License 2.0 6 votes vote down vote up
public static String determineTargetUrl(Authentication authentication) {
    Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

    if (authorities.contains(Role.DEAN_ADMIN.toString()))
        return "/admin/dean";
    else if (authorities.contains(Role.DEVELOPMENT_ADMIN.toString()))
        return "/actuator/health";
    else if (authorities.contains(Role.DEPARTMENT_ADMIN.toString()))
        return "/admin/department";
    else if (authorities.contains(Role.FACULTY.toString()))
        return "/admin/faculty/courses";
    else if (authorities.contains(Role.STUDENT.toString()))
        return "/dashboard/student/attendance";
    else if (authorities.contains(Role.USER.toString()))
        return "/profile";
    else
        return "/login";
}
 
Example 21
public UserDetails loadUserByUsername(String username)
		throws UsernameNotFoundException {
	// TODO Auto-generated method stub
	
	User user = null;
	try {
		user = userMapper.getUserByName(username);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	if(user == null)
		throw new UsernameNotFoundException("user not found!");
	//roles=角色代码
	List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles());
	userInfo = new UserInfo(username,user.getPassword(),user.isEnabled(),true,true,true,authorities);
	userInfo.setUserid(user.getUserId());
	userInfo.setRolesName(user.getRoles());
	userInfo.setTrueName(user.getTrueName());
	userInfo.setEmail(user.getEmail());
	userInfo.setPhoneNum(user.getPhoneNum());
	userInfo.setNationalId(user.getNationalId());
	userInfo.setDepId(user.getDepId());
	return userInfo;
}
 
Example 22
Source Project: batch-scheduler   Source File: JwtService.java    License: MIT License 6 votes vote down vote up
public static Authentication getAuthentication(HttpServletRequest request) {

        // 从Header中拿到token
        String token = request.getHeader(HEADER_STRING);
        if (token == null) {
            token = getTokenFromCookis(request);
        }

        if (token != null && !token.isEmpty()) {
            // 解析 Token
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            // 获取用户名
            String user = claims.get("UserId").toString();

            // 获取权限(角色)
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));

            // 返回验证令牌
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
        }
        return null;
    }
 
Example 23
Source Project: cloud-project   Source File: DomainUserDetailsService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据用户名查找账户信息并返回用户信息实体
 * @param username 用户名
 * @return 用于身份认证的 UserDetails 用户信息实体
 * @throws UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Account account = accountRepository.findByUserName(username);
    if (account!=null){
        return new User(account.getUserName(),account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
    }else {
        throw  new UsernameNotFoundException("用户["+username+"]不存在");
    }
}
 
Example 24
@Test
public void testGrantedAuthoritiesMapper() throws Exception {
    SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
    grantedAuthorityMapper.setPrefix("ROLE_");
    grantedAuthorityMapper.setConvertToUpperCase(true);
    provider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);

    Authentication result = provider.authenticate(token);
    assertEquals(Sets.newSet("ROLE_USER", "ROLE_ADMIN"),
        AuthorityUtils.authorityListToSet(result.getAuthorities()));
}
 
Example 25
Source Project: FEBS-Cloud   Source File: FebsUserDetailServiceImpl.java    License: 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 26
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
    if (!map.containsKey(AUTHORITIES)) {
        return defaultAuthorities;
    }
    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 27
Source Project: cloud-template   Source File: UserDetailsServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 构造包含用户信息的UserDetails对象。本项目仅提供用户信息,其他数据模拟
 * 应该包括:用户信息、角色信息、权限信息,这些数据都应该从数据库中查询。
 *
 * @param result
 * @return
 */
private UserDetails getUserDetails(Result<SysUser> result) {
    if (result == null || result.getData() == null) {
        throw new UsernameNotFoundException("用户不存在");
    }
    SysUser user = result.getData();

    // 模拟构造包含用户角色列表的`List<GrantedAuthority>`对象
    List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ADMIN");

    return new SctUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, authorityList);
}
 
Example 28
/**
 * 获取权限信息
 * @param map
 * @return
 */
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
    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 29
/**
 * <p>
 * Extract information about the user to be used in an access token (i.e. for resource
 * servers).
 * </p>
 * @param authentication an authentication representing a user.
 * @return a map of key values representing the unique information about the user.
 * @throws NullPointerException if authentication is {@code null}
 */
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	notNull(authentication, "authentication");
	Map<String, Object> result = new HashMap<>();
	result.put(USERNAME, authentication.getName());
	result.put(AUTHORITIES,
			AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	result.put(USERDETAILS, extractMap((UserDetails) authentication.getPrincipal()));
	return result;
}
 
Example 30
private void configClient(ClientDetailsServiceConfigurer clients) throws Exception {
    InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
    for (BaseClientDetails client : clientDetails.getClient()) {
        ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder clientBuilder =
                builder.withClient(client.getClientId());
        clientBuilder
                .secret(client.getClientSecret())
                .resourceIds(client.getResourceIds().toArray(new String[0]))
                .authorizedGrantTypes(client.getAuthorizedGrantTypes().toArray(new String[0]))
                .authorities(
                        AuthorityUtils.authorityListToSet(client.getAuthorities())
                                .toArray(new String[0]))
                .scopes(client.getScope().toArray(new String[0]));
        if (client.getAutoApproveScopes() != null) {
            clientBuilder.autoApprove(
                    client.getAutoApproveScopes().toArray(new String[0]));
        }
        if (client.getAccessTokenValiditySeconds() != null) {
            clientBuilder.accessTokenValiditySeconds(
                    client.getAccessTokenValiditySeconds());
        }
        if (client.getRefreshTokenValiditySeconds() != null) {
            clientBuilder.refreshTokenValiditySeconds(
                    client.getRefreshTokenValiditySeconds());
        }
        if (client.getRegisteredRedirectUri() != null) {
            clientBuilder.redirectUris(
                    client.getRegisteredRedirectUri().toArray(new String[0]));
        }
    }
}