Java 类org.springframework.security.core.authority.SimpleGrantedAuthority 实例源码

项目:REST-Web-Services    文件:UserDetailsServiceImpl.java   
/**
 * 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);
}
项目:spring-io    文件:JWTFilterTest.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * 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);
    }
}
项目:AntiSocial-Platform    文件:UserDetailsServiceImpl.java   
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;


    }
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:kinota-server    文件:JwtTokenUtil.java   
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);
    }
}
项目:spring-io    文件:DomainUserDetailsService.java   
@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"));
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:jhipster-microservices-example    文件:AccountResourceTest.java   
@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));
}
项目:microservices-sample-project    文件:CommonAuthenticationTokenFilter.java   
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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:smarti    文件:MongoUserDetailsService.java   
@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;
}
项目:Microservices-with-JHipster-and-Spring-Boot    文件:TokenProvider.java   
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);
}
项目:esup-sgc    文件:DatabaseUserDetailsService.java   
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);

}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:itweet-boot    文件:CustomUserService.java   
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!");
    }
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:spring-boot-oauth2-demo    文件:UserDetailsServiceImpl.java   
@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"));
}
项目:klask-io    文件:UserDetailsService.java   
@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"));
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:webcron    文件:SecurityProvider.java   
public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    UserEntity entity;
    try {
        entity = user.authenticate(String.valueOf(auth.getPrincipal()), String.valueOf(auth.getCredentials()));

        if (entity == null) {
            throw new NotFoundException(ExceptionConstants.USER_NOT_FOUND);
        }
    } catch (Exception e) {
        throw new BadCredentialsException(ExceptionConstants.PASSWORD_DOES_NOT_MATCH);
    }

    return new UsernamePasswordAuthenticationToken(UserParser.toDTO(entity), null, Collections.singletonList(new SimpleGrantedAuthority(entity.getRoles().name())));
}
项目:TorgCRM-Server    文件:JWTFilterTest.java   
@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);
}
项目:bxbot-ui-server    文件:TestJwtUser.java   
@Test
public void testInitialisationWorksAsExpected() {

    final List<Role> roles = createRoles(createUser());

    final JwtUser jwtUser = new JwtUser(USER_ID, USERNAME, FIRSTNAME, LASTNAME, PASSWORD, EMAIL, USER_ENABLED,
            LAST_PASSWORD_RESET_DATE.getTime(), createAuthorities(), roles);

    assertEquals(USER_ID, jwtUser.getId());
    assertEquals(USERNAME, jwtUser.getUsername());
    assertEquals(PASSWORD, jwtUser.getPassword());
    assertEquals(FIRSTNAME, jwtUser.getFirstname());
    assertEquals(LASTNAME, jwtUser.getLastname());
    assertEquals(EMAIL, jwtUser.getEmail());
    assertEquals(USER_ENABLED, jwtUser.isEnabled());
    assertEquals(LAST_PASSWORD_RESET_DATE.getTime(), jwtUser.getLastPasswordResetDate());

    assertTrue(jwtUser.getRoles().contains(RoleName.ROLE_ADMIN.name()));
    assertTrue(jwtUser.getRoles().contains(RoleName.ROLE_USER.name()));

    assertTrue(jwtUser.getAuthorities().contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.name())));
    assertTrue(jwtUser.getAuthorities().contains(new SimpleGrantedAuthority(RoleName.ROLE_USER.name())));
}
项目:Spring-Security-Third-Edition    文件:UserDetailsServiceImpl.java   
@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);
}
项目:springboot-sec-tutor    文件:UserDetailsServiceImpl.java   
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userService
            .getByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException(username + " not found"));
    HashSet<GrantedAuthority> authorities = new HashSet<>();
    if(user.getRoles() != null) {
        user.getRoles().stream()
                .map(Role::getName)
                .map(SimpleGrantedAuthority::new)
                .forEach(authorities::add);
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPasswordHash(), authorities);
}
项目:xm-ms-timeline    文件:OAuth2TokenMockUtil.java   
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);
}
项目:jhipster-microservices-example    文件:TokenProvider.java   
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, token, authorities);
}
项目:devoxxus-jhipster-microservices-demo    文件:SecurityUtilsUnitTest.java   
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
项目:Fetax-AI    文件:MainUserDetailServiceImpl.java   
private Set<GrantedAuthority> obtionGrantedAuthorities(Customer user) {
    //System.err.println("-----------MyUserDetailServiceImpl obtionGrantedAuthorities----------- ");
    List<Resources> resources = authService.fetchCustomerResources(String.valueOf(user.getRole()));
    Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
    for (Resources res : resources) {
        // TODO:ZZQ 用户可以访问的资源名称(或者说用户所拥有的权限) 注意:必须"ROLE_"开头
        authSet.add(new SimpleGrantedAuthority(res.getResKey()));
    }
    return authSet;
}