Java Code Examples for org.springframework.security.core.GrantedAuthority#getAuthority()

The following examples show how to use org.springframework.security.core.GrantedAuthority#getAuthority() . 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: UserDaoTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserDaowithValidUserLoginAndPassword() {

    Properties userLogins = new Properties();
    userLogins.put("admin", "ADMIN::admin123");

    UserDao user = new UserDao();
    user.setUserLogins(userLogins);
    User userBean = user.loadUserByUsername("admin");
    assertTrue(userBean.getPassword().equals("admin123"));

    Collection<? extends GrantedAuthority> authorities = userBean.getAuthorities();
    String role = "";
    for (GrantedAuthority gauth : authorities) {
        role = gauth.getAuthority();
    }
    assertTrue("ADMIN".equals(role));
}
 
Example 2
Source File: SecurityUtil.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public static boolean isAdmin() {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        Authentication authentication = context.getAuthentication();
        if (authentication != null) {
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            if (authorities != null) {
                for (GrantedAuthority authority : authorities) {
                    if (authority != null) {
                        String authorityString = authority.getAuthority();
                        
                        if (Constants.ROLE_IT_ADMINISTRATOR.equals(authorityString)) {
                            return true;
                        }
                    }
                    
                }
            }
            
        }
    }
    return false;
}
 
Example 3
Source File: CustomAuthenticationSuccessHandler.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * This method extracts the roles of currently logged-in user and returns
 * appropriate URL according to his/her role.
 */
protected String getUrl(Authentication authentication) {

    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        String role = grantedAuthority.getAuthority();
        if (role.equalsIgnoreCase(("ROLE_ADMIN"))) {
            return "/admin";
        } else if (role.equalsIgnoreCase(("ROLE_USER"))) {
            return "/home";
        } else if (role.equalsIgnoreCase(("ROLE_DBA"))) {
            return "/dba";
        } else {
            // throw new IllegalStateException();
        }
    }
    return "/";
}
 
Example 4
Source File: AuthenticationSuccessListener.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
/**
 * Authorities could be ADMIN, ROLE, SCOPE:ROLE
 * Priority is:
 * 1 - ADMIN
 * 2 - SCOPE:ROLE
 * 3 - ROLE
 * @param roleScope the scope we're looking for
 * @param authorities the authorities to parse
 * @return the role
 */
private String getRoleFromAuthorities(RoleScope roleScope, Collection<? extends GrantedAuthority> authorities) {
    String globalRole = null;
    String specificRole = null;
    for (GrantedAuthority grantedAuthority : authorities) {
        String authority = grantedAuthority.getAuthority();
        if (SystemRole.ADMIN.name().equals(authority)) {
            return authority;
        }
        if (authority.contains(":")) {
            String[] scopeAndName = authority.split(":");
            if (roleScope.name().equals(scopeAndName[0])) {
                specificRole = scopeAndName[1];
            }
        } else {
            globalRole = authority;
        }
    }
    return specificRole != null ? specificRole : globalRole;
}
 
Example 5
Source File: UserDaoTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserDaowithValidUserLoginAndPassword() {

    Properties userLogins = new Properties();
    userLogins.put("admin", "ADMIN::admin123");

    UserDao user = new UserDao();
    user.setUserLogins(userLogins);
    User userBean = user.loadUserByUsername("admin");
    assertTrue(userBean.getPassword().equals("admin123"));

    Collection<? extends GrantedAuthority> authorities = userBean.getAuthorities();
    String role = "";
    for (GrantedAuthority gauth : authorities) {
        role = gauth.getAuthority();
    }
    assertTrue("ADMIN".equals(role));
}
 
Example 6
Source File: RpcUtils.java    From Brutusin-RPC with Apache License 2.0 6 votes vote down vote up
public static Set<String> getUserRoles(Object securityContext) {
    Set<String> roleSet = new TreeSet<String>();
    if (securityContext != null) {
        SecurityContext sc = (SecurityContext) securityContext;
        if (sc.getAuthentication() != null) {
            Collection<? extends GrantedAuthority> authorities = sc.getAuthentication().getAuthorities();
            if (authorities != null) {
                for (GrantedAuthority authority : authorities) {
                    String auth = authority.getAuthority();
                    if (auth.startsWith("ROLE_")) {
                        auth = auth.substring(5);
                    }
                    roleSet.add(auth);
                }
            }
        }
    }
    return Collections.unmodifiableSet(roleSet);
}
 
Example 7
Source File: JWTAuthenticationFilter.java    From datax-web with MIT License 6 votes vote down vote up
@Override
protected void successfulAuthentication(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain chain,
                                        Authentication authResult) throws IOException {

    JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
    boolean isRemember = rememberMe.get() == 1;

    String role = "";
    Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
    for (GrantedAuthority authority : authorities){
        role = authority.getAuthority();
    }

    String token = JwtTokenUtils.createToken(jwtUser.getId(),jwtUser.getUsername(), role, isRemember);
    response.setHeader("token", JwtTokenUtils.TOKEN_PREFIX + token);
    response.setCharacterEncoding("UTF-8");
    Map<String, Object> maps = new HashMap<>();
    maps.put("data", JwtTokenUtils.TOKEN_PREFIX + token);
    maps.put("roles", role.split(SPLIT_COMMA));
    response.getWriter().write(JSON.toJSONString(new ReturnT<>(maps)));
}
 
Example 8
Source File: CustomerUserDetails.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
    if (g2.getAuthority() == null) {
        return -1;
    }

    if (g1.getAuthority() == null) {
        return 1;
    }

    return g1.getAuthority().compareTo(g2.getAuthority());
}
 
Example 9
Source File: RbacUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
public static String buildRoleCode(GrantedAuthority role) {
	String result = role.getAuthority();
	if (role instanceof SysRole) {
		result = RoleType.SYS_ROLE.name() + ":" + result;
	}
	else {
		result = RoleType.APP_ROLE.name() + ":" + result;
	}
	return result;
}
 
Example 10
Source File: SpringSecurityHelper.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private Subject buildSubject(final Authentication authentication) {
    Subject s = new Subject();
    s.getPrincipals().add(new SimplePrincipal(authentication == null ? ANONYMOUS:authentication.getName()));
    if (authentication != null) {
        SimpleGroup g = new SimpleGroup("Roles");
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            String role = ga.getAuthority();
            g.addMember(new SimplePrincipal(role));
        }
        s.getPrincipals().add(g);
    }
    return s;
}
 
Example 11
Source File: UserDetailsImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
	// Neither should ever be null as each entry is checked before adding it to the set.
	// If the authority is null, it is a custom authority and should precede others.
	if (g2.getAuthority() == null) {
		return -1;
	}

	if (g1.getAuthority() == null) {
		return 1;
	}

	return g1.getAuthority().compareTo(g2.getAuthority());
}
 
Example 12
Source File: SecurityUtils.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
public static Set<String> getCurrentAuthorityUrl() {
	Set<String> path = Sets.newHashSet();
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
	for (final GrantedAuthority authority : authorities) {
		String url = authority.getAuthority();
		if (StringUtils.isNotEmpty(url)) {
			path.add(url);
		}
	}
	path.add(AUTH_LOGIN_AFTER_URL);
	path.add(AUTH_LOGOUT_URL);
	return path;
}
 
Example 13
Source File: IdolLoginSuccessHandler.java    From find with MIT License 5 votes vote down vote up
@Override
protected String determineTargetUrl(final HttpServletRequest request, final HttpServletResponse response) {
    final Authentication authentication = authenticationInformationRetriever.getAuthentication();

    for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        final String authority = grantedAuthority.getAuthority();

        if (roleDefault.equalsIgnoreCase(authority)) {
            return configUrl;
        }
    }

    return applicationUrl;
}
 
Example 14
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 15
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 16
Source File: CustomAccessDecisionManager.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * 判定是否拥有权限的决策方法
 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
 * @param o 包含客户端发起的请求的request信息。
 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
    String url;
    for (GrantedAuthority ga : authentication.getAuthorities()) {
         url = ga.getAuthority();
         if(url.equals(request.getRequestURI())){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
Example 17
Source File: CustomAccessDecisionManager.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * 判定是否拥有权限的决策方法
 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
 * @param o 包含客户端发起的请求的request信息。
 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
    String url;
    for (GrantedAuthority ga : authentication.getAuthorities()) {
         url = ga.getAuthority();
         if(url.equals(request.getRequestURI())){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
Example 18
Source File: CustomAccessDecisionManager.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * 判定是否拥有权限的决策方法
 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
 * @param o 包含客户端发起的请求的request信息。
 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
    String url;
    for (GrantedAuthority ga : authentication.getAuthorities()) {
         url = ga.getAuthority();
         if(url.equals(request.getRequestURI())){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
Example 19
Source File: AuthorityImpl.java    From attic-rave with Apache License 2.0 4 votes vote down vote up
public AuthorityImpl(GrantedAuthority grantedAuthority) {
    this(grantedAuthority.getAuthority());
}
 
Example 20
Source File: GrantedAuthorityImpl.java    From haven-platform with Apache License 2.0 2 votes vote down vote up
/**
 * create instance with data from specified authority
 * @param authority
 * @return
 */
public static GrantedAuthorityImpl from(GrantedAuthority authority) {
    return new GrantedAuthorityImpl(authority.getAuthority(), MultiTenancySupport.getTenant(authority));
}