java类org.springframework.security.core.userdetails.User的实例源码

TokenProvider.java 文件源码 项目:Microservices-with-JHipster-and-Spring-Boot 阅读 22 收藏 0 点赞 0 评论 0
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);
}
TokenProvider.java 文件源码 项目:klask-io 阅读 34 收藏 0 点赞 0 评论 0
public Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

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

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

    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 23 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
AccountResourceTest.java 文件源码 项目:jhipster-microservices-example 阅读 30 收藏 0 点赞 0 评论 0
@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));
}
MainUserDetailServiceImpl.java 文件源码 项目:Fetax-AI 阅读 24 收藏 0 点赞 0 评论 0
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    //System.err.println("-----------MyUserDetailServiceImpl loadUserByUsername ----------- ");
    //取得用户的权限
    Customer user = authService.findCustomer(userName);
    if  (user==null)  
           throw new UsernameNotFoundException(userName+" not exist!");  
    Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
    // 封装成spring security的user
    User userdetail = new User(
            user.getName(), 
            user.getPassword(),
            true, 
            true, 
            true,
            true, 
            grantedAuths    //用户的权限
        );
    return userdetail;
}
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 23 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
AuthorizationServerConfig.java 文件源码 项目:cloud-project 阅读 26 收藏 0 点赞 0 评论 0
/**
 * Jwt资源令牌转换器
 * @return accessTokenConverter
 */
@Bean
public JwtAccessTokenConverter accessTokenConverter(){
    return new JwtAccessTokenConverter(){

        /**
         * 重写增强token的方法
         * @param accessToken 资源令牌
         * @param authentication 认证
         * @return 增强的OAuth2AccessToken对象
         */
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

            String userName = authentication.getUserAuthentication().getName();
            User user = (User) authentication.getUserAuthentication().getPrincipal();
            Map<String,Object> infoMap = new HashMap<>();
            infoMap.put("userName",userName);
            infoMap.put("roles",user.getAuthorities());
            ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(infoMap);
            return super.enhance(accessToken, authentication);
        }
    };
}
MeasureUserActivityFilterTestBase.java 文件源码 项目:tqdev-metrics 阅读 26 收藏 0 点赞 0 评论 0
/**
 * Simulate a request with authenticated user with specified username for a
 * specified duration in nanoseconds.
 *
 * @param username
 *            the username
 * @param durationInNanoseconds
 *            the duration in nanoseconds
 */
protected void request(String username, long durationInNanoseconds) {
    long now = 1510373758000000000L;
    when(registry.getNanos()).thenReturn(now, now + durationInNanoseconds);

    if (username != null) {
        User user = new User(username, "", new ArrayList<GrantedAuthority>());
        Authentication auth = new UsernamePasswordAuthenticationToken(user, null);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    try {
        filter.doFilterInternal(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
                mock(FilterChain.class));
    } catch (ServletException | IOException e) {
        e.printStackTrace();
    }
}
WebSecurityAuthenticationConfigurer.java 文件源码 项目:chvote-protocol-poc 阅读 24 收藏 0 点赞 0 评论 0
@Bean
UserDetailsService userDetailsService() {
    return username -> {
        LOGGER.debug(String.format("Looking for user [%s]", username));
        Account account = accountRepository.findByUsername(username);
        if (account != null) {
            LOGGER.info(String.format("Found user [%s]", username));
            return new User(account.getUsername(), account.getPassword(),
                    true, true, true, true,
                    AuthorityUtils.createAuthorityList("USER"));
        } else {
            LOGGER.info(String.format("Couldn't find user [%s]", username));
            throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username));
        }
    };
}
SecurityConfiguration.java 文件源码 项目:JenkinsHue 阅读 22 收藏 0 点赞 0 评论 0
@Bean
public UserDetailsService userDetailsService() {
    return userName -> {
           UserDTO user = userAuthenticationProvider.userService.findByLogin(userName.toLowerCase());
           if (user == null) {
               throw new UsernameNotFoundException(userName);
           }

           Set<SimpleGrantedAuthority> userAuthorities = new HashSet<>();
           List<Role> roles = user.getRoles();
           if (roles != null) {
               for (Role role : roles) {
                   userAuthorities.add(new SimpleGrantedAuthority(role.toString()));
               }
           }

           return new User(userName, userName /* TODO use password */, userAuthorities);
       };
}
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 26 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
SecurityConfiguration.java 文件源码 项目:demo-spring-boot-security-oauth2 阅读 24 收藏 0 点赞 0 评论 0
@Bean
public UserDetailsService userDetailsService() {
    return new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
            // 通过用户名获取用户信息
            Account account = accountRepository.findByName(name);
            if (account != null) {
                // 创建spring security安全用户
                User user = new User(account.getName(), account.getPassword(),
                        AuthorityUtils.createAuthorityList(account.getRoles()));
                return user;
            } else {
                throw new UsernameNotFoundException("用户[" + name + "]不存在");
            }
        }
    };

}
GrantedAuthoritiesFromAssertionAttributesWithDefaultRolesUserDetailsService.java 文件源码 项目:cas-security-spring-boot-starter 阅读 24 收藏 0 点赞 0 评论 0
protected UserDetails loadUserDetails(Assertion assertion) {
    String username = assertion.getPrincipal().getName();
    if (!StringUtils.hasText(username)) {
        throw new UsernameNotFoundException("Unable to retrieve username from CAS assertion");
    }

    List<GrantedAuthority> authorities = Arrays
            .stream(attributes)
            .map(a -> assertion.getPrincipal().getAttributes().get(a))
            .filter(Objects::nonNull)
            .flatMap(v -> (v instanceof Collection) ? ((Collection<?>) v).stream() : Stream.of(v))
            .map(v -> toUppercase ? v.toString().toUpperCase() : v.toString())
            .map(r -> r.replaceFirst("^ROLE_", ""))
            .map(r -> new SimpleGrantedAuthority("ROLE_" + r))
            .collect(Collectors.toList());

    authorities.addAll(defaultGrantedAuthorities);

    return new User(username, NON_EXISTENT_PASSWORD_VALUE, authorities);
}
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 20 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 24 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
SecurityServiceConfiguration.java 文件源码 项目:JavaRestCalculator 阅读 21 收藏 0 点赞 0 评论 0
@Autowired
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    LOG.info("Registering global user details service");
    auth.userDetailsService(username -> {
        try {
            BillingUser user = billingDao.loadUser(username);
            return new User(
                    user.getUsername(),
                    user.getPassword(),
                    Collections.singletonList(() -> "AUTH")
            );
        } catch (EmptyResultDataAccessException e) {
            LOG.warn("No such user: " + username);
            throw new UsernameNotFoundException(username);
        }
    });
}
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 23 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
SpringSecurityUserContext.java 文件源码 项目:Spring-Security-Third-Edition 阅读 25 收藏 0 点赞 0 评论 0
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
CustomUserService.java 文件源码 项目:itweet-boot 阅读 23 收藏 0 点赞 0 评论 0
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!");
    }
}
JwtTokenUtil.java 文件源码 项目:kinota-server 阅读 20 收藏 0 点赞 0 评论 0
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);
    }
}
CustomUserDetailsRepository.java 文件源码 项目:spring-webflux-microservices-boilerplate 阅读 26 收藏 0 点赞 0 评论 0
@Override public Mono<UserDetails> findByUsername(String username) {
  return userRepository.findByUsr(username)
      .flatMap(user -> Mono.just(User
          .withUsername(user.getUsr())
          .password(user.getPwd())
          .roles(user.getRole())
          .authorities(user.getAuthorities())
          .accountExpired(user.isAccountNonExpiredAlias())
          .accountLocked(user.isAccountNonLockedAlias())
          .credentialsExpired(user.isCredentialsNonExpiredAlias())
          .disabled(user.isEnabledAlias()).build()));
}
LearningSpringBootConfigServer.java 文件源码 项目:Learning-Spring-Boot-2.0-Second-Edition 阅读 24 收藏 0 点赞 0 评论 0
@Bean
UserDetailsService userDetailsService() {
    return new InMemoryUserDetailsManager(
        User
            .withUsername("user")
            .password("password")
            .roles("USER").build());
}
SpringDataUserDetailsRepository.java 文件源码 项目:Learning-Spring-Boot-2.0-Second-Edition 阅读 25 收藏 0 点赞 0 评论 0
@Override
public Mono<UserDetails> findByUsername(String username) {
    return repository.findByUsername(username)
        .map(user -> new User(
            user.getUsername(),
            user.getPassword(),
            AuthorityUtils.createAuthorityList(user.getRoles())
        ));
}
SecurityUtils.java 文件源码 项目:shoucang 阅读 37 收藏 0 点赞 0 评论 0
/**
 * Return the current user, or throws an exception, if the user is not
 * authenticated yet.
 *
 * @return the current user
 */
public static User getCurrentUser() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof User) {
            return (User) authentication.getPrincipal();
        }
    }
    throw new IllegalStateException("User not found!");
}
LearningSpringBootEurekaServerApplication.java 文件源码 项目:Learning-Spring-Boot-2.0-Second-Edition 阅读 19 收藏 0 点赞 0 评论 0
@Bean
UserDetailsService userDetailsService() {
    return new InMemoryUserDetailsManager(
        User
            .withUsername("user")
            .password("password")
            .roles("USER").build());
}
DomainUserDetailsService.java 文件源码 项目:cloud-project 阅读 51 收藏 0 点赞 0 评论 0
/**
 * 根据用户名查找账户信息并返回用户信息实体
 * @param username 用户名
 * @return 用于身份认证的 UserDetails 用户信息实体
 * @throws UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Account account = accountRepository.findByUserName(username);
    if (account!=null){
        return new User(account.getUserName(),account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
    }else {
        throw  new UsernameNotFoundException("用户["+username+"]不存在");
    }
}
AccountUserDetailsService.java 文件源码 项目:oauth2-with-jdbc 阅读 21 收藏 0 点赞 0 评论 0
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return accountRepository
            .findByUsername(username)
            .map(account -> new User(account.getUsername(), account.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER")))
            .orElseThrow(() -> new UsernameNotFoundException("Could not find " + username));
}
AbstractSecurityTest.java 文件源码 项目:bootstrap 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Initialize {@link SecurityContextHolder} for given user.
 * 
 * @param user
 *            the user to set in the context.
 * @param authorities
 *            the optional authorities name
 * @return The configured {@link SecurityContext}.
 */
@SuppressWarnings("unchecked")
protected SecurityContext initSpringSecurityContext(final String user, final GrantedAuthority... authorities) {
    SecurityContextHolder.clearContext();
    final SecurityContext context = Mockito.mock(SecurityContext.class);
    final Authentication authentication = Mockito.mock(Authentication.class);
    final List<GrantedAuthority> authoritiesAsList = Arrays.asList(authorities);
    final User userDetails = new User(user, USER_DETAILS_NA, authoritiesAsList);
    Mockito.when((List<GrantedAuthority>) authentication.getAuthorities()).thenReturn(authoritiesAsList);
    Mockito.when(context.getAuthentication()).thenReturn(authentication);
    Mockito.when(authentication.getPrincipal()).thenReturn(userDetails);
    Mockito.when(authentication.getName()).thenReturn(user);
    SecurityContextHolder.setContext(context);
    return context;
}
AccountResource.java 文件源码 项目:jhipster-microservices-example 阅读 32 收藏 0 点赞 0 评论 0
/**
 * GET  /account : get the current user.
 *
 * @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server
 * Error) if the user couldn't be returned
 */
@GetMapping("/account")
@Timed
public ResponseEntity<UserVM> getAccount() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    try{
        User user = (User) authentication.getPrincipal();
        UserVM userVM = new UserVM(user.getUsername(),
            user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority).collect(Collectors.toSet()));
        return new ResponseEntity<>(userVM, HttpStatus.OK);
    } catch (NullPointerException | ClassCastException e){
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
TokenProvider.java 文件源码 项目:jhipster-microservices-example 阅读 25 收藏 0 点赞 0 评论 0
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);
}


问题


面经


文章

微信
公众号

扫码关注公众号