Java Code Examples for org.springframework.security.core.userdetails.User#getAuthorities()

The following examples show how to use org.springframework.security.core.userdetails.User#getAuthorities() . 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: CustomPermissionEvaluator.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
@Override
public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
    // 获得loadUserByUsername()方法的结果
    User user = (User) authentication.getPrincipal();
    // 获得loadUserByUsername()中注入的角色
    Collection<GrantedAuthority> authorities = user.getAuthorities();

    // 遍历用户所有角色
    for (GrantedAuthority authority : authorities) {
        String roleName = authority.getAuthority();
        Integer roleId = roleService.selectByName(roleName).getId();
        // 得到角色所有的权限
        List<SysPermission> permissionList = permissionService.listByRoleId(roleId);

        // 遍历权限
        for (SysPermission sysPermission : permissionList) {
            // 获取权限集
            List permissions = sysPermission.getPermissions();
            // 如果访问的Url和权限用户符合的话,返回true
            if (targetUrl.equals(sysPermission.getUrl())
                    && permissions.contains(targetPermission)) {
                return true;
            }
        }

    }

    return false;
}
 
Example 2
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 3
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 4
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 5
Source File: SAMLUserDetailsServiceImplTest.java    From spring-boot-security-saml-sample with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadUserBySAML() {
    // given
    NameID mockNameID = mock(NameID.class);
    when(mockNameID.getValue()).thenReturn(USER_NAME);

    SAMLCredential credentialsMock = mock(SAMLCredential.class);
    when(credentialsMock.getNameID()).thenReturn(mockNameID);

    // when
    Object actual = userDetailsService.loadUserBySAML(credentialsMock);

    // / then
    assertNotNull(actual);
    assertTrue(actual instanceof User);

    User user = (User)actual;
    assertEquals(USER_NAME, user.getUsername());
    assertEquals(USER_PASSWORD, user.getPassword());
    assertTrue(user.isEnabled());
    assertTrue(user.isAccountNonExpired());
    assertTrue(user.isCredentialsNonExpired());
    assertTrue(user.isAccountNonLocked());
    assertEquals(1, user.getAuthorities().size());

    List<GrantedAuthority> authorities = new ArrayList<>(user.getAuthorities());
    Object authority = authorities.get(0);

    assertTrue(authority instanceof SimpleGrantedAuthority);
    assertEquals(USER_ROLE, ((SimpleGrantedAuthority)authority).getAuthority());
}
 
Example 6
Source File: UserService.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    User predefinedUser = predefinedUsers.get(email);
    if (predefinedUser == null) {
        return Optional.ofNullable(players.getByEmail(email))
                .map(player -> buildUserDetails(player.getEmail(), player.getPassword(), ROLE_USER))
                .orElse(null);
    }
    return new User(predefinedUser.getUsername(), predefinedUser.getPassword(), predefinedUser.getAuthorities());
}
 
Example 7
Source File: SecurityContextAuthenticator.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private boolean isAdmin(SecurityContext context) {
    if (context.getAuthentication() == null) {
        return false;
    }

    Authentication authentication = context.getAuthentication();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        if (token.getPrincipal() instanceof String) {
            return token.getPrincipal().equals(config.getAdminLogin()) &&
                    token.getCredentials().equals(config.getAdminPassword());
        }
    }

    Object principal = authentication.getPrincipal();

    if (!(principal instanceof User)) {
        return false;
    }

    User user = (User) principal;
    if (user == null) {
        return false;
    }

    Collection<GrantedAuthority> authorities = user.getAuthorities();
    if (authorities == null) {
        return false;
    }

    return authorities.contains(ROLE_ADMIN.authority());
}
 
Example 8
Source File: DefaultJwtSecurityTokenService.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public JwtSecurityTokenInfo generateToken(Authentication authentication){
	if(authentication==null){
		return null;
	}
	
	LoginUserDetails userDetails = null;
	if(authentication.getPrincipal() instanceof LoginUserDetails){
		userDetails = (LoginUserDetails)authentication.getPrincipal();
	}else{
		User user = (User)authentication.getPrincipal();
		userDetails = new LoginUserDetails(0L, user.getUsername(), "N/A", user.getAuthorities());
	}
	Collection<String> authorities = userDetails.getAuthorities()
									.stream()
									.map(auth->auth.getAuthority())
									.collect(Collectors.toSet());
	String authoritiesString = GuavaUtils.join(authorities, ",");
	DateTime issuteAt = DateTime.now();
	Date expirationDate = issuteAt.plusSeconds(getExpirationInSeconds().intValue()).toDate();
	String token = Jwts.builder()
						.setSubject(userDetails.getUsername())
						.claim(JwtSecurityUtils.CLAIM_USER_ID, userDetails.getUserId())
						.claim(JwtSecurityUtils.CLAIM_AUTHORITIES, authoritiesString)
						.setIssuedAt(issuteAt.toDate())
						.setExpiration(expirationDate)
						.signWith(SignatureAlgorithm.HS512, securityConfig.getJwt().getSigningKey())
						.compact();
	
	return JwtSecurityTokenInfo.builder()
						.token(token)
						.build();
}
 
Example 9
Source File: OneOpsUser.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new OneOps user from the {@link UserDetails} object.
 *
 * @param user user details.
 */
public OneOpsUser(User user) {
  this(
      user.getUsername(),
      user.getPassword(),
      user.getAuthorities(),
      user.getUsername(),
      AuthDomain.PROD);
}
 
Example 10
Source File: LoginSuccessHandler.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to create {@link OneOpsUser} for authentication principal.
 *
 * @param principal authentication principal
 * @return oneops user.
 */
private OneOpsUser getOneOpsUser(User principal) {
  log.debug("Found user details in authentication. Creating OneOps User.");
  String userName = principal.getUsername();
  String password = principal.getPassword();

  if (password == null) {
    log.debug(userName + " credentials are already erased.");
    password = "";
  }
  return new OneOpsUser(
      userName, password, principal.getAuthorities(), userName, AuthDomain.PROD);
}
 
Example 11
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 12
Source File: DefaultPermissionEvaluator.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
    // 获得loadUserByUsername()方法的结果
    User user = (User)authentication.getPrincipal();
    // 获得loadUserByUsername()中注入的角色
    Collection<GrantedAuthority> authorities = user.getAuthorities();

    // 遍历用户所有角色
    for(GrantedAuthority authority : authorities) {
        String roleName = authority.getAuthority();
        Integer roleId = roleService.getByName(roleName).getId();
        // 得到角色所有的权限
        List<SysPermission> permissionList = permissionService.listByRoleId(roleId);

        // 遍历permissionList
        for(SysPermission sysPermission : permissionList) {
            // 获取权限集
            List permissions = sysPermission.getPermissions();
            // 如果访问的Url和权限用户符合的话,返回true
            if(targetUrl.equals(sysPermission.getUrl())
                    && permissions.contains(targetPermission)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 13
Source File: DefaultPermissionEvaluator.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
    // 获得loadUserByUsername()方法的结果
    User user = (User)authentication.getPrincipal();
    // 获得loadUserByUsername()中注入的角色
    Collection<GrantedAuthority> authorities = user.getAuthorities();

    // 遍历用户所有角色
    for(GrantedAuthority authority : authorities) {
        String roleName = authority.getAuthority();
        Integer roleId = roleService.getByName(roleName).getId();
        // 得到角色所有的权限
        List<SysPermission> permissionList = permissionService.listByRoleId(roleId);

        // 遍历permissionList
        for(SysPermission sysPermission : permissionList) {
            // 获取权限集
            List permissions = sysPermission.getPermissions();
            // 如果访问的Url和权限用户符合的话,返回true
            if(targetUrl.equals(sysPermission.getUrl())
                    && permissions.contains(targetPermission)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 14
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 15
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 16
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 17
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 18
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 19
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example 20
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}