當前位置: 首頁>>代碼示例>>Java>>正文


Java GrantedAuthority類代碼示例

本文整理匯總了Java中org.springframework.security.core.GrantedAuthority的典型用法代碼示例。如果您正苦於以下問題:Java GrantedAuthority類的具體用法?Java GrantedAuthority怎麽用?Java GrantedAuthority使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


GrantedAuthority類屬於org.springframework.security.core包,在下文中一共展示了GrantedAuthority類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getAuthentication

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public Authentication getAuthentication(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token != null) {
        // parse the token.
        String user = getUsername(token);

        String roles = getBody(token).get("roles", String.class);
        List<GrantedAuthority> grantedAuths =
                AuthorityUtils.commaSeparatedStringToAuthorityList(roles);

        return user != null ?
                new UsernamePasswordAuthenticationToken(user, null,
                        grantedAuths) :
                null;
    }
    return null;
}
 
開發者ID:Clcanny,項目名稱:MicroServiceDemo,代碼行數:18,代碼來源:JwtTokenUtil.java

示例2: loadUserByUsername

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    CalendarUser user = userRepository.findByEmail(username);

    if (user == null)
        throw new UsernameNotFoundException("username " + username
                + " not found");

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:18,代碼來源:UserDetailsServiceImpl.java

示例3: loadUserByUsername

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (StringUtils.isBlank(username)) {
        throw new UsernameNotFoundException("用戶名為空");
    }
    String password;
    TUser tUser = iUserService.getByUsername(username);
    if(tUser==null){
        throw new UsernameNotFoundException("登錄賬號不存在");
    }else{
        password=tUser.getPassword();
    }

    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority("USER"));
    return new org.springframework.security.core.userdetails.User(
            username, password,
            true,
            true,
            true,
            true,
            authorities);
}
 
開發者ID:fier-liu,項目名稱:FCat,代碼行數:24,代碼來源:GateUserDetailsService.java

示例4: authenticate

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
public Authentication authenticate(Authentication auth){
 Usuario user = userRepository.findByEmail(auth.getName());
 if (user == null) {
	 throw new BadCredentialsException("User not found");
 }
 String password = (String) auth.getCredentials();
 if (!new BCryptPasswordEncoder().matches(password, user.getContraseña())) {
	 throw new BadCredentialsException("Wrong password");
 }

 List<GrantedAuthority> roles = new ArrayList<>();
 for (String role : user.getRol()) {
	 roles.add(new SimpleGrantedAuthority(role));
	 }
 return new UsernamePasswordAuthenticationToken(user.getEmail(), password, roles);
}
 
開發者ID:jeche21,項目名稱:SaleWeb,代碼行數:18,代碼來源:UsuarioRepositoryAuthenticationProvider.java

示例5: getAuthorities

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public static List<String> getAuthorities() {
    Authentication authentication = getAuthentication();

    if (authentication == null) {
        return Collections.EMPTY_LIST;
    }

    Collection<? extends GrantedAuthority> grantedAuthorityList = authentication
            .getAuthorities();

    List<String> authorities = new ArrayList<String>();

    for (GrantedAuthority grantedAuthority : grantedAuthorityList) {
        authorities.add(grantedAuthority.getAuthority());
    }

    return authorities;
}
 
開發者ID:zhaojunfei,項目名稱:lemon,代碼行數:19,代碼來源:SpringSecurityUtils.java

示例6: authenticate

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:21,代碼來源:CalendarUserAuthenticationProvider.java

示例7: createToken

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public String createToken(Authentication authentication, Boolean rememberMe) {
    String authorities = authentication.getAuthorities().stream()
        .map(GrantedAuthority::getAuthority)
        .collect(Collectors.joining(","));

    long now = (new Date()).getTime();
    Date validity;
    if (rememberMe) {
        validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
    } else {
        validity = new Date(now + this.tokenValidityInMilliseconds);
    }

    return Jwts.builder()
        .setSubject(authentication.getName())
        .claim(AUTHORITIES_KEY, authorities)
        .signWith(SignatureAlgorithm.HS512, secretKey)
        .setExpiration(validity)
        .compact();
}
 
開發者ID:oktadeveloper,項目名稱:jhipster-microservices-example,代碼行數:21,代碼來源:TokenProvider.java

示例8: create

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public static UserContext create(String tenantId, String orgId, List<GrantedAuthority> authorities) {
  
  if (authorities == null || authorities.isEmpty()) {
    throw new IllegalArgumentException("No authorities");
  }
  
  Optional<GrantedAuthority> maybeSuperAdmin
    = authorities.stream()
      .filter(authority -> authority.getAuthority().equals("ROLE_SUPER_ADMIN")).findAny();
  
  if (maybeSuperAdmin.isPresent()) {
    return new UserContext("*", "*", authorities);
  }

  Optional<GrantedAuthority> maybeTenantAdmin
  = authorities.stream()
    .filter(authority -> authority.getAuthority().equals("ROLE_TENANT_ADMIN")).findAny();

  if (maybeTenantAdmin.isPresent()) {
    return new UserContext(tenantId, "*", authorities);
  }
 
  return new UserContext(tenantId, orgId, authorities);
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:25,代碼來源:UserContext.java

示例9: doGetGrantedResources

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
private List<Resource> doGetGrantedResources(List<? extends Resource> existedResources,
											 List<GrantedAuthority> roles) {
	List<Resource> result = new ArrayList<>();

	//always return the open resource
	existedResources.stream().filter(res -> res.isOpen()).forEach(res -> result.add(res));
	//and return the granted resource
	existedResources.stream().filter(res -> !res.isOpen()).forEach(resource -> {
		for (GrantedAuthority role : roles) {
			ResourceRoleRelationship resourceRoleRelationship = resourceRoleRelationshipRepository.findByResourceCodeAndRoleCode(
					resource.getCode(),
					RbacUtils.buildRoleCode(role));
			if (resourceRoleRelationship != null) {
				result.add(resource);
				break;
			}
		}
	});

	return result;
}
 
開發者ID:melthaw,項目名稱:spring-backend-boilerplate,代碼行數:22,代碼來源:PermissionServiceImpl.java

示例10: JwtUser

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public JwtUser(
      Long id,
      String username,
      String firstname,
      String lastname,
      String email,
      String password, Collection<? extends GrantedAuthority> authorities,
      boolean enabled,
      Date lastPasswordResetDate
) {
    this.id = id;
    this.username = username;
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
    this.password = password;
    this.authorities = authorities;
    this.enabled = enabled;
    this.lastPasswordResetDate = lastPasswordResetDate;
}
 
開發者ID:adriano-fonseca,項目名稱:rest-api-jwt-spring-security,代碼行數:21,代碼來源:JwtUser.java

示例11: loadUserByUsername

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
    return userFromDatabase.map(user -> {
        if (!user.getActivated()) {
            throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
        }
        List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getName()))
            .collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(lowercaseLogin,
            user.getPassword(),
            grantedAuthorities);
    }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
    "database"));
}
 
開發者ID:deepu105,項目名稱:spring-io,代碼行數:20,代碼來源:DomainUserDetailsService.java

示例12: getGrantedAuthorities

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
    Collection<? extends GrantedAuthority> authorities = delegate.getGrantedAuthorities(userData, username);

    if (authorities != null) {
        return authorities.stream()
                          .map(GrantedAuthority::getAuthority)
                          .map(a -> authorityToPermissionMap.get(a))
                          .filter(Objects::nonNull)
                          .filter(a -> !a.isEmpty())
                          .map(SimpleGrantedAuthority::new)
                          .collect(Collectors.toSet());
    } else {
        return null;
    }
}
 
開發者ID:LIBCAS,項目名稱:ARCLib,代碼行數:17,代碼來源:RewriteAuthoritiesPopulator.java

示例13: enhance

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal();

    String roles = "";
    List<GrantedAuthority> grantedAuthorities = (List<GrantedAuthority>) customUserDetails.getAuthorities();
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        roles = roles.concat(" " + grantedAuthority.getAuthority());
    }
    roles = roles.trim();

    Map<String, Object> additionalInfo = new HashMap<>();
    additionalInfo.put("uuid", customUserDetails.getId());
    additionalInfo.put("role", roles);
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
開發者ID:tadeucruz,項目名稱:spring-oauth2-jwt,代碼行數:18,代碼來源:JWTTokenEnhancer.java

示例14: isAuthorized

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
/**
 * Check the authorization
 */
private boolean isAuthorized(final Collection<? extends GrantedAuthority> authorities, final String request, final HttpMethod method) {
	final Map<String, Map<HttpMethod, List<Pattern>>> authorizationsCache = authorizationResource.getAuthorizations().get(
			AuthorizationType.API);

	// Check the authorization
	if (authorizationsCache != null) {
		for (final GrantedAuthority authority : authorities) {
			final Map<HttpMethod, List<Pattern>> authorizations = authorizationsCache.get(authority.getAuthority());
			if (authorizations != null && match(authorizations.get(method), request)) {
				// Granted access
				return true;
			}
		}
	}

	// No authorization found
	return false;
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:22,代碼來源:AuthorizingFilter.java

示例15: getCurrentRoles

import org.springframework.security.core.GrantedAuthority; //導入依賴的package包/類
public Set<String> getCurrentRoles() {
	Set<String> roles = new HashSet<String>();
	try {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth!=null && auth.isAuthenticated()) {
			Object principal = auth.getPrincipal();
			if (principal instanceof UserDetails) {
				for (GrantedAuthority ga : ((UserDetails)principal).getAuthorities()) {
					roles.add(ga.getAuthority());
				}
			}
		}
	} catch (Exception e) {
		log.error("Can't get roles", e);
	}
	return roles;
}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:18,代碼來源:YadaSecurityUtil.java


注:本文中的org.springframework.security.core.GrantedAuthority類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。