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

The following examples show how to use org.springframework.security.core.Authentication#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: AppAuthenticationFilter.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
		Authentication authResult) throws IOException, ServletException {

	System.out.println("AUTH FILTER");
	
	
	Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
	List<String> roles = new ArrayList<String>();
	for (GrantedAuthority a : authorities) {
		roles.add(a.getAuthority());
	}
	System.out.println(roles);
	
	String name = obtainPassword(request);
       String password = obtainUsername(request);
	
       
	UsernamePasswordAuthenticationToken userDetails = new UsernamePasswordAuthenticationToken(name, password, authorities);
	setDetails(request, userDetails);	
	chain.doFilter(request, response);
}
 
Example 2
Source File: SecurityUtils.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Returns whether the current user has at least one of the given roles */
public static boolean currentUserHasRole(String... roles) {
  if (roles == null || roles.length == 0) return false;

  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication != null) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    if (authorities == null) throw new IllegalStateException("No user currently logged in");

    for (String role : roles) {
      for (GrantedAuthority grantedAuthority : authorities) {
        if (role.equals(grantedAuthority.getAuthority())) return true;
      }
    }
  }
  return false;
}
 
Example 3
Source File: FileAuthenticationTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserRoleMapping() {

    when(authentication.getName()).thenReturn("admin");
    when(authentication.getCredentials()).thenReturn("admin");

    Authentication auth = authProvider.authenticate(authentication);
    LOG.debug(" {}", auth);

    assertTrue(auth.isAuthenticated());

    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    String role = "";
    for (GrantedAuthority gauth : authorities) {
        role = gauth.getAuthority();
    }
    assertTrue("ADMIN".equals(role));
}
 
Example 4
Source File: AuthenticationController.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
/**
    * Retrieves the pre authenticated user
    * @param authentication
    * @return
    */
   @RequestMapping(value = "/api/secured/user", method = { RequestMethod.GET }, produces = ApplicationMediaType.APPLICATION_BEARCHOKE_V1_JSON_VALUE)
public AuthenticationToken getUser(Authentication authentication) {
       UserDetails principal = (UserDetails) authentication.getPrincipal();
       Collection<GrantedAuthority> credentials = (Collection<GrantedAuthority>) authentication.getAuthorities();

       final Map<String, Boolean> roles = new HashMap<>();

       for (GrantedAuthority authority : credentials) {
           roles.put(authority.getAuthority(), true);
       }

       AuthenticationToken at;

       if (principal instanceof UserDetailsExtended) {
           UserDetailsExtended ude = (UserDetailsExtended) principal;
           at = new AuthenticationToken(ude.getUsername(), ude.getName(), ude.getFirstName(), ude.getLastName(), ude.getProfilePictureUrl(), roles);
       } else {
           at = new AuthenticationToken(principal.getUsername(), roles);
       }

       return at;
}
 
Example 5
Source File: ModuleAccessVoter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Votes. Votes ACCESS_ABSTAIN if the object class is not supported. Votes
 * ACCESS_GRANTED if there is a granted authority which equals attribute
 * prefix + module name, or the module name is in the always accessible set.
 * Otherwise votes ACCESS_DENIED.
 */
@Override
public int vote( Authentication authentication, Object object, Collection<ConfigAttribute> attributes )
{
    if ( !supports( object.getClass() ) )
    {
        log.debug( "ACCESS_ABSTAIN [" + object.toString() + "]: Class not supported." );

        return ACCESS_ABSTAIN;
    }

    ActionConfig target = (ActionConfig) object;

    if ( alwaysAccessible.contains( target.getPackageName() ) )
    {
        log.debug( "ACCESS_GRANTED [" + target.getPackageName() + "] by configuration." );

        return ACCESS_GRANTED;
    }

    String requiredAuthority = attributePrefix + target.getPackageName();

    for ( GrantedAuthority grantedAuthority : authentication.getAuthorities() )
    {
        if ( grantedAuthority.getAuthority().equals( requiredAuthority ) )
        {
            log.debug( "ACCESS_GRANTED [" + target.getPackageName() + "]" );

            return ACCESS_GRANTED;
        }
    }

    log.debug( "ACCESS_DENIED [" + target.getPackageName() + "]" );

    return ACCESS_DENIED;
}
 
Example 6
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	Map<String, Object> response = new LinkedHashMap<String, Object>();
	response.put("sub", authentication.getName());
	if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
		response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	}
	return response;
}
 
Example 7
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	Map<String, Object> response = new LinkedHashMap<String, Object>();
	response.put("sub", authentication.getName());
	if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
		response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	}
	return response;
}
 
Example 8
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 9
Source File: AccessManager.java    From open-cloud with MIT License 5 votes vote down vote up
public boolean mathAuthorities(HttpServletRequest request, Authentication authentication, String requestPath) {
    Collection<ConfigAttribute> attributes = getAttributes(requestPath);
    int result = 0;
    int expires = 0;
    if (authentication == null) {
        return false;
    } else {
        if (CommonConstants.ROOT.equals(authentication.getName())) {
            // 默认超级管理员账号,直接放行
            return true;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Iterator var6 = attributes.iterator();
        while (var6.hasNext()) {
            ConfigAttribute attribute = (ConfigAttribute) var6.next();
            Iterator var8 = authorities.iterator();
            while (var8.hasNext()) {
                GrantedAuthority authority = (GrantedAuthority) var8.next();
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    result++;
                    if (authority instanceof OpenAuthority) {
                        OpenAuthority customer = (OpenAuthority) authority;
                        if (customer.getIsExpired() != null && customer.getIsExpired()) {
                            // 授权过期数
                            expires++;
                        }
                    }
                }
            }
        }
        log.debug("mathAuthorities result[{}] expires[{}]", result, expires);
        if (expires > 0) {
            // 授权已过期
            throw new AccessDeniedException(ErrorCode.ACCESS_DENIED_AUTHORITY_EXPIRED.getMessage());
        }
        return result > 0;
    }
}
 
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: AdminRoleVoter.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    for (GrantedAuthority authority : authentication.getAuthorities()) {
        if (authority.getAuthority().equals(Authorities.ADMIN_ROLE)) {
            return ACCESS_GRANTED;
        }
    }
    return super.vote(authentication, object, attributes);
}
 
Example 12
Source File: IsAdminMethod.java    From todolist with MIT License 5 votes vote down vote up
@Override
public Object exec(List arguments) throws TemplateModelException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean result = false;
    for(GrantedAuthority each : auth.getAuthorities()) {
        if(each.getAuthority().equals("ROLE_ADMIN")) {
            result = true;
            break;
        }
    }
    return result;
}
 
Example 13
Source File: CustomUserAuthenticationConverter.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
    Map<String, Object> response = new LinkedHashMap<String, Object>();
    response.put(USERNAME, authentication.getName());
    if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
        response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
    }
    return response;
}
 
Example 14
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	Map<String, Object> response = new LinkedHashMap<String, Object>();
	response.put("sub", authentication.getName());
	if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
		response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	}
	return response;
}
 
Example 15
Source File: CustomerAccessTokenConverter.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
    LinkedHashMap<String, Object> response = new LinkedHashMap<>();
    response.put("details", authentication.getDetails());
    response.put("test", "hello");
    if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
        response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
    }
    return response;
}
 
Example 16
Source File: DefaultUserAuthenticationConverter.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
	Map<String, Object> response = new LinkedHashMap<String, Object>();
	response.put(USERNAME, authentication.getName());
	if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
		response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
	}
	return response;
}
 
Example 17
Source File: PermissionService.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 判断接口是否有xxx:xxx权限
 *
 * @param permission 权限
 * @return {boolean}
 */
public boolean hasPermission(String permission) {
	if (StrUtil.isBlank(permission)) {
		return false;
	}
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (authentication == null) {
		return false;
	}
	Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
	return authorities.stream()
		.map(GrantedAuthority::getAuthority)
		.filter(StringUtils::hasText)
		.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
}
 
Example 18
Source File: AuthContextUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void updateUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, FAKE_PASSWORD, auth.getAuthorities()),
            auth.getCredentials(), auth.getAuthorities());
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}
 
Example 19
Source File: AdminResource.java    From atlas with Apache License 2.0 4 votes vote down vote up
@GET
@Path("session")
@Produces(Servlets.JSON_MEDIA_TYPE)
public Response getUserProfile() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> AdminResource.getUserProfile()");
    }

    Response response;

    boolean isEntityUpdateAccessAllowed = false;
    boolean isEntityCreateAccessAllowed = false;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String userName = null;
    Set<String> groups = new HashSet<>();
    if (auth != null) {
        userName = auth.getName();
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        for (GrantedAuthority c : authorities) {
            groups.add(c.getAuthority());
        }

        isEntityUpdateAccessAllowed = AtlasAuthorizationUtils.isAccessAllowed(new AtlasEntityAccessRequest(typeRegistry, AtlasPrivilege.ENTITY_UPDATE));
        isEntityCreateAccessAllowed = AtlasAuthorizationUtils.isAccessAllowed(new AtlasEntityAccessRequest(typeRegistry, AtlasPrivilege.ENTITY_CREATE));
    }

    Map<String, Object> responseData = new HashMap<>();

    responseData.put(isCSRF_ENABLED, AtlasCSRFPreventionFilter.isCSRF_ENABLED);
    responseData.put(BROWSER_USER_AGENT_PARAM, AtlasCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
    responseData.put(CUSTOM_METHODS_TO_IGNORE_PARAM, AtlasCSRFPreventionFilter.METHODS_TO_IGNORE_DEFAULT);
    responseData.put(CUSTOM_HEADER_PARAM, AtlasCSRFPreventionFilter.HEADER_DEFAULT);
    responseData.put(isEntityUpdateAllowed, isEntityUpdateAccessAllowed);
    responseData.put(isEntityCreateAllowed, isEntityCreateAccessAllowed);
    responseData.put(editableEntityTypes, getEditableEntityTypes(atlasProperties));
    responseData.put(DEFAULT_UI_VERSION, defaultUIVersion);
    responseData.put("userName", userName);
    responseData.put("groups", groups);
    responseData.put("timezones", TIMEZONE_LIST);

    response = Response.ok(AtlasJson.toV1Json(responseData)).build();

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== AdminResource.getUserProfile()");
    }

    return response;
}
 
Example 20
Source File: TokenAuthenticationHelper.java    From SpringSecurity-JWT-Vue-Deom with MIT License 4 votes vote down vote up
/**
 * 设置登陆成功后令牌返回
 * */
public static void addAuthentication(HttpServletRequest request,  HttpServletResponse response, Authentication authResult) throws IOException {
    // 获取用户登陆角色
    Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
    // 遍历用户角色
    StringBuffer stringBuffer = new StringBuffer();
    authorities.forEach(authority -> {
        stringBuffer.append(authority.getAuthority()).append(",");
    });
    long expirationTime = EXPIRATION_TIME;
    int cookExpirationTime = -1;
    // 处理登陆附加信息
    LoginDetails loginDetails = (LoginDetails) authResult.getDetails();
    if (loginDetails.getRememberMe() != null && loginDetails.getRememberMe()) {
        expirationTime = COOKIE_EXPIRATION_TIME * 1000;
        cookExpirationTime = COOKIE_EXPIRATION_TIME;
    }

    String jwt = Jwts.builder()
            // Subject 设置用户名
            .setSubject(authResult.getName())
            // 设置用户权限
            .claim("authorities", stringBuffer)
            // 过期时间
            .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
            // 签名算法
            .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
            .compact();
    Cookie cookie = new Cookie(COOKIE_TOKEN, jwt);
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    cookie.setMaxAge(cookExpirationTime);
    response.addCookie(cookie);

    // 向前端写入数据
    LoginResultDetails loginResultDetails = new LoginResultDetails();
    ResultDetails resultDetails = new ResultDetails();
    resultDetails.setStatus(HttpStatus.OK.value());
    resultDetails.setMessage("登陆成功!");
    resultDetails.setSuccess(true);
    resultDetails.setTimestamp(LocalDateTime.now());
    User user = new User();
    user.setUsername(authResult.getName());
    user.setPower(stringBuffer.toString());
    user.setExpirationTime(System.currentTimeMillis() + expirationTime);

    loginResultDetails.setResultDetails(resultDetails);
    loginResultDetails.setUser(user);
    loginResultDetails.setStatus(200);
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write(new ObjectMapper().writeValueAsString(loginResultDetails));
    out.flush();
    out.close();
}