Java Code Examples for org.springframework.security.core.authority.AuthorityUtils#commaSeparatedStringToAuthorityList()

The following examples show how to use org.springframework.security.core.authority.AuthorityUtils#commaSeparatedStringToAuthorityList() . 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: TokenAuthentication.java    From opscenter with Apache License 2.0 6 votes vote down vote up
/**
 * 根据JWT获取验证令牌
 * @param request
 * @return
 */
public static Authentication getAuthentication(HttpServletRequest request) {
       // 从Header中拿到token
       String token = request.getHeader(HEADER_STRING);
       if (StringUtils.isEmpty(token)) token = CookiesUtil.getCookieValueByName(request, HEADER_STRING);
	if (StringUtils.isEmpty(token)) return null;
       // 解析 Token
       Claims claims = Jwts.parser()
               // 验签
			.setSigningKey(SECRET)
               // 去掉 Bearer
			.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
			.getBody();

       // 拿用户名
       String user = claims.getSubject();

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

       // 返回验证令牌
       return user != null ?
			new UsernamePasswordAuthenticationToken(user, null, authorities) :
			null;
}
 
Example 2
Source File: UserConfig.java    From base-admin with 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 3
Source File: UserDetailService.java    From SpringAll with 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 4
Source File: UserDetailService.java    From SpringAll with 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 5
Source File: JwtTokenUtils.java    From black-shop with Apache License 2.0 6 votes vote down vote up
/**
 * Get auth Info
 *
 * @param token token
 * @return auth info
 */
public Authentication getAuthentication(String token) {
    /**
     *  parse the payload of token
     */
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

    List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY));


    User principal = new User(claims.getSubject(), "", authorities);
    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
Example 6
Source File: InMemoryIdentityLookup.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    boolean found = true;
    int userIdx = 0;

    while (found) {
        String user = environment.getProperty("users[" + userIdx + "].user");
        found = (user != null && user.isEmpty());

        if (found) {
            String username = environment.getProperty("users[" + userIdx + "].username");
            String password = environment.getProperty("users[" + userIdx + "].password");
            String email = environment.getProperty("users[" + userIdx + "].email");
            String firstname = environment.getProperty("users[" + userIdx + "].firstname");
            String lastname = environment.getProperty("users[" + userIdx + "].lastname");
            String roles = environment.getProperty("users[" + userIdx + "].roles");
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
            userIdx++;

            io.gravitee.rest.api.idp.api.authentication.UserDetails newUser = new io.gravitee.rest.api.idp.api.authentication.UserDetails(username, password, email, authorities);

            newUser.setSource(InMemoryIdentityProvider.PROVIDER_TYPE);
            newUser.setSourceId(username);
            newUser.setFirstname(firstname);
            newUser.setLastname(lastname);
            userDetailsService.createUser(newUser);
        }
    }

    // Get a reference to stored users
    Field fieldUser = userDetailsService.getClass().getDeclaredField("users");
    boolean accessible = fieldUser.isAccessible();
    fieldUser.setAccessible(true);
    users = (Set<String>) ((Map) fieldUser.get(userDetailsService)).keySet();
    fieldUser.setAccessible(accessible);
}
 
Example 7
Source File: UserDetailsManagerImpl.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    QueryWrapper<User> query = new QueryWrapper<>();
    User user = userMapper.selectOne(query.eq("userName", userName));
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
        true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
 
Example 8
Source File: UserDetailsServiceImpl.java    From microservices-spring-boot with MIT License 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	
	// hard coding the users. All passwords must be encoded.
	final List<AppUser> users = Arrays.asList(
		new AppUser(1, "omar", encoder.encode("12345"), "USER"),
		new AppUser(2, "admin", encoder.encode("12345"), "ADMIN")
	);
	

	for(AppUser appUser: users) {
		if(appUser.getUsername().equals(username)) {
			
			// Remember that Spring needs roles to be in this format: "ROLE_" + userRole (i.e. "ROLE_ADMIN")
			// So, we need to set it to that format, so we can verify and compare roles (i.e. hasRole("ADMIN")).
			List<GrantedAuthority> grantedAuthorities = AuthorityUtils
	                	.commaSeparatedStringToAuthorityList("ROLE_" + appUser.getRole());
			
			// The "User" class is provided by Spring and represents a model class for user to be returned by UserDetailsService
			// And used by auth manager to verify and check user authentication.
			return new User(appUser.getUsername(), appUser.getPassword(), grantedAuthorities);
		}
	}
	
	// If user not found. Throw this exception.
	throw new UsernameNotFoundException("Username: " + username + " not found");
}
 
Example 9
Source File: PkiSecurityConfiguration.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
@Bean
@Override
public UserDetailsService userDetailsService() {
    return (username -> {
        if (properties.getAuthentication().getFlairBi().getPki().getSubjects().contains(username)) {
            return new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        } else {
            throw new UsernameNotFoundException("Invalid response");
        }
    });
}
 
Example 10
Source File: UserDetailService.java    From SpringAll with MIT License 5 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());

    return new User(username, user.getPassword(), user.isEnabled(),
            user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
 
Example 11
Source File: MyUserDetailsService.java    From imooc-security with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    logger.info("登陆用户名:"+username);
    //根据用户名查找用户信息
    String password = passwordEncoder.encode("123456");
    logger.info("数据库密码是:"+password);
    return new User(username,password,
            true,true,true,true,
            AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
 
Example 12
Source File: SpringSocialTokenServices.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication extractAuthentication(UserProfile user) {
	String principal = user.getUsername();
	List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
	OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null, null, null, null, null);
	return new OAuth2Authentication(request,
			new UsernamePasswordAuthenticationToken(principal, "N/A", authorities));
}
 
Example 13
Source File: UserDetailService.java    From SpringAll with MIT License 5 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"));

    return new User(username, user.getPassword(), user.isEnabled(),
            user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("user:add"));
}
 
Example 14
Source File: CustomUserAuthenticationConverter.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
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 15
Source File: BaseClientDetails.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public BaseClientDetails(String clientId, String resourceIds,
		String scopes, String grantTypes, String authorities,
		String redirectUris) {

	this.clientId = clientId;

	if (StringUtils.hasText(resourceIds)) {
		Set<String> resources = StringUtils
				.commaDelimitedListToSet(resourceIds);
		if (!resources.isEmpty()) {
			this.resourceIds = resources;
		}
	}

	if (StringUtils.hasText(scopes)) {
		Set<String> scopeList = StringUtils.commaDelimitedListToSet(scopes);
		if (!scopeList.isEmpty()) {
			this.scope = scopeList;
		}
	}

	if (StringUtils.hasText(grantTypes)) {
		this.authorizedGrantTypes = StringUtils
				.commaDelimitedListToSet(grantTypes);
	} else {
		this.authorizedGrantTypes = new HashSet<String>(Arrays.asList(
				"authorization_code", "refresh_token"));
	}

	if (StringUtils.hasText(authorities)) {
		this.authorities = AuthorityUtils
				.commaSeparatedStringToAuthorityList(authorities);
	}

	if (StringUtils.hasText(redirectUris)) {
		this.registeredRedirectUris = StringUtils
				.commaDelimitedListToSet(redirectUris);
	}
}
 
Example 16
Source File: SecurityConfig.java    From java-examples with MIT License 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService() {
    return (UserDetailsService) username -> {
        if (username.equals("pavel")) {
            return new User(username, "",
                    AuthorityUtils
                            .commaSeparatedStringToAuthorityList("ROLE_USER"));
        } else {
            throw new UsernameNotFoundException(String.format("User %s not found", username));
        }
    };
}
 
Example 17
Source File: CustomerAccessTokenConverter.java    From spring-boot-demo with MIT License 5 votes vote down vote up
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
  if (!map.containsKey("authorities")) {
    return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.arrayToCommaDelimitedString(new String[]{"USER"}));
  } else {
    Object authorities = map.get("authorities");
    if (authorities instanceof String) {
      return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
    } else if (authorities instanceof Collection) {
      return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection) authorities));
    } else {
      throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
  }
}
 
Example 18
Source File: CustomUserDetails.java    From black-shop with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    // TODO: get authorities
    return AuthorityUtils.commaSeparatedStringToAuthorityList("");
}
 
Example 19
Source File: CustomUserAuthenticationConverter.java    From microservices-oauth with Apache License 2.0 4 votes vote down vote up
public void setDefaultAuthorities(String[] defaultAuthorities) {
	this.defaultAuthorities = AuthorityUtils
			.commaSeparatedStringToAuthorityList(StringUtils.arrayToCommaDelimitedString(defaultAuthorities));
}
 
Example 20
Source File: BootClientDetails.java    From oauth-boot with MIT License 4 votes vote down vote up
@Override
public Collection<GrantedAuthority> getAuthorities() {
    return (client.getAuthorities()!=null&&client.getAuthorities().trim().length()>0)?
            AuthorityUtils.commaSeparatedStringToAuthorityList(client.getAuthorities()):null;
}