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

The following examples show how to use org.springframework.security.core.userdetails.UserDetails#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: JwtAuthenticationTokenFilter.java    From HIS with Apache License 2.0 9 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 2
Source File: _CustomSignInAdapter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example 3
Source File: SmsStaffServiceImpl.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override
public String login(String username, String password) {
    String token = null;
    //密码需要客户端加密后传递
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);//返回的是一个userDetails的实现类AdminUserDetails
        if(!passwordEncoder.matches(password,userDetails.getPassword())){  //password是从前端过来未经过编译的,而userDetails.getPassword()是从数据库中出来经过编译的
            throw new BadCredentialsException("密码不正确");
        }
        //创建一个新的token
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);  //在securityContext中添加该验证信息
        token = jwtTokenUtil.generateToken(userDetails);
        //updateLoginTimeByUsername(username);
        //insertLoginLog(username);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example 4
Source File: CustomDaoAuthenticationProvider.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    UserDetails u = null;

    try {
        u = getUserDetailsService().loadUserByUsername(name);
    } catch (UsernameNotFoundException ex) {
        log.error("User '" + name + "' not found");
    } catch (Exception e) {
        log.error("Exception in CustomDaoAuthenticationProvider: " + e);
    }

    if (u != null) {
        if (u.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(u, password, u.getAuthorities());
        }
    }

    throw new BadCredentialsException(messages.getMessage("CustomDaoAuthenticationProvider.badCredentials", "Bad credentials"));

}
 
Example 5
Source File: SecurityConfigurer.java    From sample-boot-micro with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() == null ||
            authentication.getCredentials() == null) {
        throw new BadCredentialsException("ログイン認証に失敗しました");
    }
    SecurityActorService service = actorFinder.detailsService();
    UserDetails details = service.loadUserByUsername(authentication.getPrincipal().toString());
    String presentedPassword = authentication.getCredentials().toString();
    if (!encoder.matches(presentedPassword, details.getPassword())) {
        throw new BadCredentialsException("ログイン認証に失敗しました");
    }
    UsernamePasswordAuthenticationToken ret = new UsernamePasswordAuthenticationToken(
            authentication.getName(), "", details.getAuthorities());
    ret.setDetails(details);
    return ret;
}
 
Example 6
Source File: JwtAuthenticationTokenFilter.java    From macrozheng with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 7
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 8
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 9
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 10
Source File: DhisWebSpringTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected UsernamePasswordAuthenticationToken getPrincipal( String... authorities )
{
    User user = createAdminUser( authorities );
    List<GrantedAuthority> grantedAuthorities = user.getUserCredentials().getAllAuthorities()
        .stream().map( SimpleGrantedAuthority::new ).collect( Collectors.toList() );

    UserDetails userDetails = new org.springframework.security.core.userdetails.User(
        user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuthorities );

    return new UsernamePasswordAuthenticationToken(
        userDetails,
        userDetails.getPassword(),
        userDetails.getAuthorities()
    );
}
 
Example 11
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 12
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(),userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 13
Source File: SecurityServiceImpl.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Override
public void autoLogin(String username, String password) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    authenticationManager.authenticate(usernamePasswordAuthenticationToken);

    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        logger.debug(String.format("Auto login %s successfully!", username));
    }
}
 
Example 14
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 15
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 16
Source File: SecurityServiceImpl.java    From registration-login-spring-xml-maven-jsp-mysql with MIT License 5 votes vote down vote up
@Override
public void autologin(String username, String password) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    authenticationManager.authenticate(usernamePasswordAuthenticationToken);

    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        logger.debug(String.format("Auto login %s successfully!", username));
    }
}
 
Example 17
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example 18
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 19
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 20
Source File: MiniAppAuthenticationToken.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
public MiniAppAuthenticationToken(UserDetails principal, Object credentials) {
    super(principal, credentials, principal.getAuthorities());
}