当前位置: 首页>>代码示例>>Java>>正文


Java SimpleGrantedAuthority类代码示例

本文整理汇总了Java中org.springframework.security.core.authority.SimpleGrantedAuthority的典型用法代码示例。如果您正苦于以下问题:Java SimpleGrantedAuthority类的具体用法?Java SimpleGrantedAuthority怎么用?Java SimpleGrantedAuthority使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SimpleGrantedAuthority类属于org.springframework.security.core.authority包,在下文中一共展示了SimpleGrantedAuthority类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
/**
 * Get user by username. Login process.
 *
 * @param username The user's name
 * @return UserDetails object
 * @throws UsernameNotFoundException No user found
 */
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    log.info("Called with username {}", username);

    Optional<UserEntity> userOptional = userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username);

    userOptional.orElseThrow(() -> new UsernameNotFoundException("No user found with username " + username));

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for(SecurityRole role : userOptional.get().getAuthorities()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.toString()));
    }

    return new org.springframework.security.core.userdetails.User(userOptional.get().getUsername(),
                                                                  userOptional.get().getPassword(),
                                                                  grantedAuthorities);
}
 
开发者ID:JonkiPro,项目名称:REST-Web-Services,代码行数:25,代码来源:UserDetailsServiceImpl.java

示例2: testJWTFilter

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:19,代码来源:JWTFilterTest.java

示例3: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的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

示例4: alimenteSecurityUserCptMin

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
/**
 * Alimente la session pour un compte local
 * 
 * @param cptMin
 *            le compte a minima a connecter
 */
public void alimenteSecurityUserCptMin(CompteMinima cptMin) {
	SecurityUser user = (SecurityUser) getCurrentUser();
	if (user != null) {
		List<GrantedAuthority> authoritiesListe = new ArrayList<GrantedAuthority>();
		SimpleGrantedAuthority sga = new SimpleGrantedAuthority(ConstanteUtils.ROLE_CANDIDAT);
		authoritiesListe.add(sga);

		SecurityUserCandidat securityUserCandidat = new SecurityUserCandidat(user.getUsername(),
				user.getDisplayName(), authoritiesListe, cptMin.getIdCptMin(), cptMin.getNumDossierOpiCptMin(),
				cptMin.getTemValidCptMin(), cptMin.getTemValidMailCptMin(), null);
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				securityUserCandidat, securityUserCandidat.getUsername(), securityUserCandidat.getAuthorities());
		Authentication authentication = authenticationManagerCandidat.authenticate(authRequest);
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authentication);
		SecurityContextHolder.setContext(context);
		UI.getCurrent().getSession().getSession()
				.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
	}
}
 
开发者ID:EsupPortail,项目名称:esup-ecandidat,代码行数:27,代码来源:UserController.java

示例5: getGrantedAuthorities

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
private List<GrantedAuthority> getGrantedAuthorities(User user) {

        /*
        For now users can only have 1 role at a time. You cannot have more than 1 role type.
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        UserDetail userDetail = user.getUserDetail();
        String[] list = (userDetail.getType()).split(",");
        for(String i : list){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+i));
        }
         return authorities;
        */

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getUserDetail().getType()));
       return authorities;


    }
 
开发者ID:Exercon,项目名称:AntiSocial-Platform,代码行数:21,代码来源:UserDetailsServiceImpl.java

示例6: parseUserFromToken

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public User parseUserFromToken(String token) {
    try {
        String username = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        String roleString = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token).getBody().get("roles", String.class);
        List<SimpleGrantedAuthority> roles = new ArrayList<>();
        if (!StringUtils.isEmpty(roleString)) {
            String[] roleValues = StringUtils.split(roleString, ",");
            for (String roleValue : roleValues) {
                roles.add(new SimpleGrantedAuthority(roleValue));
            }
        }
        return new User(username, token, roles);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
        throw new BadCredentialsException("Invalid JWT token: ", ex);
    } catch (ExpiredJwtException expiredEx) {
        throw new JwtExpiredTokenException("JWT Token expired", expiredEx);
    }
}
 
开发者ID:kinota,项目名称:kinota-server,代码行数:25,代码来源:JwtTokenUtil.java

示例7: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的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

示例8: testGetExistingAccount

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Test
public void testGetExistingAccount() throws Exception {

    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);

    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
开发者ID:oktadeveloper,项目名称:jhipster-microservices-example,代码行数:21,代码来源:AccountResourceTest.java

示例9: prepareUserDetails

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
private UserDetails prepareUserDetails(String jsonUserDetails) throws JsonProcessingException, IOException{
	
	ObjectMapper objectMapper = new ObjectMapper();
	JsonNode root = objectMapper.readTree(jsonUserDetails);
	
	String userId = root.get("dbUser").get("id").asText();
	String username = root.get("username").asText();
	boolean isEnabled =  root.get("enabled").asBoolean();
	
	List<SimpleGrantedAuthority> authorities = new ArrayList<>();
	
	Iterator<JsonNode> authoritiesIterator = root.get("authorities").elements();
	while(authoritiesIterator.hasNext()){
		JsonNode authorityNode = authoritiesIterator.next();
		authorities.add(new SimpleGrantedAuthority(authorityNode.get("authority").asText()));
	}
	
	return new AuthUser(userId, username, authorities, isEnabled);
}
 
开发者ID:quebic-source,项目名称:microservices-sample-project,代码行数:20,代码来源:CommonAuthenticationTokenFilter.java

示例10: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
public AttributedUserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
    login = login.toLowerCase(Locale.ROOT);

    final SmartiUser smartiUser = getSmaritUser(login);

    if (smartiUser == null) {
        log.debug("User {} not found", login);
        throw new UsernameNotFoundException(String.format("Unknown user: '%s'", login));
    }

    final MongoUserDetails userDetails = new MongoUserDetails(
            smartiUser.getLogin(),
            smartiUser.getPassword(),
            Collections2.transform(smartiUser.getRoles(),
                    role -> new SimpleGrantedAuthority("ROLE_" + StringUtils.upperCase(role, Locale.ROOT))
            )
    );
    userDetails.addAttributes(smartiUser.getProfile());
    return userDetails;
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:22,代码来源:MongoUserDetailsService.java

示例11: getAuthentication

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

    Collection<? extends GrantedAuthority> authorities =
        Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());

    User principal = new User(claims.getSubject(), "",
        authorities);

    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
开发者ID:IBM,项目名称:Microservices-with-JHipster-and-Spring-Boot,代码行数:17,代码来源:TokenProvider.java

示例12: loadUserByUser

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public UserDetails loadUserByUser(User targetUser)
		throws UsernameNotFoundException {

	List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
 
	resynchronisationUserService.synchronizeUserInfo(targetUser.getEppn());
	ldapGroup2UserRoleService.syncUser(targetUser.getEppn());
	
	for(String role : targetUser.getRoles()) {
		authorities.add(new SimpleGrantedAuthority(role));
	}

	return new org.springframework.security.core.userdetails.User(targetUser.getEppn(), "dummy", 
			true, // enabled
			true, // account not expired
			true, // credentials not expired
			true, // account not locked
			authorities);

}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:21,代码来源:DatabaseUserDetailsService.java

示例13: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public UserDetails loadUserByUsername(String username) {
    SysUser user = userRepository.findByUsername(username);
    if (user != null) {
        List<SysPermission> permissions = permissionRepository.findByAdminUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
        for (SysPermission permission : permissions) {
            if (permission != null && permission.getName()!=null) {

            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
            grantedAuthorities.add(grantedAuthority);
            }
        }
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    } else {
        throw new UsernameNotFoundException("admin: " + username + " do not exist!");
    }
}
 
开发者ID:realxujiang,项目名称:itweet-boot,代码行数:18,代码来源:CustomUserService.java

示例14: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    
    Optional<User> userFromDatabase = findOneWithAuthoritiesByLogin(login);
    return userFromDatabase.map(user -> {
        if (!user.getActivated()) {
            throw new UserNotActivatedException("User " + login + " was not activated");
        }
        List<GrantedAuthority> grantedAuthorities =
                user.getAuthorities()
                    .stream()
                    .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                    .collect(Collectors.toList());
        
         
        return new RichUserDetails(user.getId(),user.getPhone(),user.getLoginName(),user.getPasswordHash(), grantedAuthorities);
        
    }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the " +
            "database"));
}
 
开发者ID:sdcuike,项目名称:spring-boot-oauth2-demo,代码行数:23,代码来源:UserDetailsServiceImpl.java

示例15: loadUserByUsername

import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userFromDatabase = userRepository.findOneByLogin(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:klask-io,项目名称:klask-io,代码行数:20,代码来源:UserDetailsService.java


注:本文中的org.springframework.security.core.authority.SimpleGrantedAuthority类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。