Java 类org.springframework.security.web.authentication.WebAuthenticationDetailsSource 实例源码

项目:springboot-rest-api-skeleton    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String authToken = request.getHeader(this.tokenHeader);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    filterChain.doFilter(request, response);

}
项目:jwtExample    文件:AuthenticationTokenFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    String username = this.tokenUtils.getUsernameFromToken(authToken);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        if (this.tokenUtils.validateToken(authToken, userDetails)) {

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:spring-jwt-starter    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        logger.info("checking authentication for user " + username);
        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        JwtUser userDetails = (JwtUser)this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:microservices-sample-project    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication user " + 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 + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:spring-boot-jwt-jpa    文件:AuthenticationController.java   
@ApiOperation("get token")
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<TokenRes> createAuthenticationToken(@Valid @ModelAttribute JwtAuthenticationReq authenticationRequest, HttpServletRequest httpServletRequest) throws AuthenticationException {

    // Perform the security
    String username = authenticationRequest.getUsername();
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

    if (!passwordEncoder.matches(authenticationRequest.getPassword(), userDetails.getPassword())) {
        throw new BadCredentialsException(username);
    }

    // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
    // the database compellingly. Again it's up to you ;)
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
    LOGGER.info("authenticated user {}, setting security context", username);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Reload password post-security so we can generate token
    String token = jwtTokenUtil.generateToken(username);
    LOGGER.info("username:{},token:{}", username, token);
    // Return the token
    return ResponseEntity.ok(new TokenRes(token));
}
项目:pokemon    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication user " + 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 + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:ponto-inteligente-api    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String token = request.getHeader(AUTH_HEADER);
    if (token != null && token.startsWith(BEARER_PREFIX)) {
        token = token.substring(7);
    }
    String username = jwtTokenUtil.getUsernameFromToken(token);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.tokenValido(token)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:chvote-protocol-poc    文件:JwtAuthenticationTokenFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    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(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:borabeber-api    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String token = request.getHeader(AUTH_HEADER);
    if (token != null && token.startsWith(BEARER_PREFIX)) {
        token = token.substring(7);
    }
    String username = jwtTokenUtil.getUsernameFromToken(token);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.tokenValido(token)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:jwt-spring-boot-security    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    // TODO: 10.09.16 have to determine how important this prefix is. maybe configurable?
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    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(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:alpha-umi    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(AUTH_HEADER_NAME);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger1.info("checking authentication find user " + 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));
            logger1.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:meditor    文件:JwtAuthTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
    FilterChain chain) throws ServletException, IOException {
  String authToken = request.getHeader(this.tokenHeader);
  if (authToken != null && authToken.startsWith(TOKEN_PREFIX)) {
    authToken = authToken.substring(TOKEN_PREFIX.length());
    String username = jwtService.getUsernameFromToken(authToken);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

      if (jwtService.validateToken(authToken, userDetails)) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            userDetails, null, userDetails.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        logger.info("authenticated user " + username + ", setting security context");
        SecurityContextHolder.getContext().setAuthentication(authentication);
      }
    }
  }

  chain.doFilter(request, response);
}
项目:SMSC    文件:JWTAuthenticationTokenFilter.java   
/**
 * This method will be be invoked once per request within a single request thread.
 * Base method which is used to check user authorities using tokens during any request.
 * <p>
 * Implementation of basic {@link org.springframework.web.filter.OncePerRequestFilter
 * #doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain)}  method.
 *
 * @param request  the request, in which method will be executed
 * @param response the response
 * @param chain    an object provided by the servlet container to the developer
 *                 giving a view into the invocation chain of a filtered request
 *                 for a resource
 * @throws ServletException if {@code request} or {@code response} are not {@link HttpServletRequest}
 *                          or {@link HttpServletResponse} type accordingly
 * @throws IOException      on input error
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    String username = jwtTokenGenerationService.getUsernameFromToken(authToken);

    if (username != null) {
        LOG.info(String.format("Checking authentication for user %s ", username));
        try {
            JWTUser jwtUser = this.userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            LOG.info(String.format("Authenticated user %s, setting security context", username));
            LOG.info(String.format("%s has authorities: %s", username, jwtUser.getAuthorities()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (UsernameNotFoundException e) {
            LOG.info(String.format("User %s not found.", username));
        }
    }

    chain.doFilter(request, response);
}
项目:CleverWeb    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String token = request.getHeader(tokenHeader);
    if (token != null ) {
        String username = jwtTokenUtil.getUsernameFromToken(token);
        logger.info("checking authentication " + username);

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            // 如果我们足够相信token中的数据,也就是我们足够相信签名token的secret的机制足够好
            // 这种情况下,我们可以不用再查询数据库,而直接采用token中的数据
            // 本例中,我们还是通过Spring Security的 @UserDetailsService 进行了数据查询
            // 但简单验证的话,你可以采用直接验证token是否合法来避免昂贵的数据查询
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                logger.info("authenticated user " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }

    chain.doFilter(request, response);
}
项目:nikita-noark5-core    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication für user " + username);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:jwt-with-spring    文件:JwtAuthenticationTokenFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String header = httpRequest.getHeader("Authorization");
    final SecurityContext context = SecurityContextHolder.getContext();
    if (header != null && context.getAuthentication() == null) {
        final String tokenStr = header.substring("Bearer ".length());
        final JwtToken token = jwtTokenCodec.decodeToken(tokenStr);
        if (!token.isExpired()) {
            final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(token, "n/a", token.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            context.setAuthentication(authentication);
        }
    }
    chain.doFilter(request, response);
}
项目:Cerberus    文件:AuthenticationTokenFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

  HttpServletRequest httpRequest = (HttpServletRequest) request;
  String authToken = httpRequest.getHeader(this.tokenHeader);
  String username = this.tokenUtils.getUsernameFromToken(authToken);

  if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
    if (this.tokenUtils.validateToken(authToken, userDetails)) {
      UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
      authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
      SecurityContextHolder.getContext().setAuthentication(authentication);
    }
  }

  chain.doFilter(request, response);
}
项目:montgomery    文件:AuthenticationTokenProcessingFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String authToken = this.extractAuthTokenFromRequest(httpRequest);
    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {

        UserDetails userDetails = this.userService
                .loadUserByUsername(userName);

        if (TokenUtils.validateToken(authToken, userDetails)) {

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource()
                    .buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(
                    authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:sakai    文件:JwtAuthenticationTokenFilter.java   
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

    String header = request.getHeader(this.tokenHeader);
    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = header.substring(7);

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return SecurityContextHolder.getContext().getAuthentication();
}
项目:token-based-rest-auth    文件:AuthenticationTokenProcessingFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException
{
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String authToken = this.extractAuthTokenFromRequest(httpRequest);
    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {

        UserDetails user = this.userDetailsService.loadUserByUsername(userName);

        if (TokenUtils.validateToken(authToken, user)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:jersey-angular    文件:AuthenticationTokenProcessingFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException
{
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String authToken = this.extractAuthTokenFromRequest(httpRequest);
    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {

        UserDetails userDetails = this.userService.loadUserByUsername(userName);

        if (TokenUtils.validateToken(authToken, userDetails)) {

            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:montgomery    文件:AuthenticationTokenProcessingFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String authToken = this.extractAuthTokenFromRequest(httpRequest);
    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {

        UserDetails userDetails = this.userService
                .loadUserByUsername(userName);

        if (TokenUtils.validateToken(authToken, userDetails)) {

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource()
                    .buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(
                    authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:sakai    文件:JwtAuthenticationTokenFilter.java   
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

    String header = request.getHeader(this.tokenHeader);
    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = header.substring(7);

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return SecurityContextHolder.getContext().getAuthentication();
}
项目:kontempl    文件:AuthenticationTokenProcessingFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String token = this.extractAuthTokenIdFromRequest(httpRequest);
    logger.debug("Token found: " + token);
    if (token != null) {
        AuthToken authToken = userService.getCurrentAuthToken(token);

        if (authToken != null) {
            User user = authToken.getUser();
            logger.debug("User retrieved: " + user);

            UserDetails userDetails = new OptiUserDetails(user, user.getRoles());
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.debug("security context updated with user details");
        }
    }

    chain.doFilter(request, response);
}
项目:Practical-Microservices    文件:JwtAuthenticationTokenFilter.java   
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    String header_authorization = httpServletRequest.getHeader("Authorization");
    String token = (StringUtils.isBlank(header_authorization) ? null : header_authorization.split(" ")[1]);

    if (StringUtils.isBlank(header_authorization) && token == null) {
        logger.info("Token Not found in header.");
    } else {

        UserDetails principal = null;
        try {
            principal = authBuilder.getDefaultUserDetailsService().loadUserByUsername(token);
            UsernamePasswordAuthenticationToken userAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    principal, "", principal.getAuthorities());
            userAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(userAuthenticationToken);
        } catch (Exception e) {
            HttpServletResponse httpresposne = (HttpServletResponse) response;
            httpresposne.setContentType("application/json");
            httpresposne.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            ObjectMapper jsonMapper = new ObjectMapper();
            PrintWriter out = httpresposne.getWriter();
            Map<String, String> jsonResponse = new HashMap<String, String>();
            jsonResponse.put("msg", "Invalid Token");
            out.write(jsonMapper.writeValueAsString(jsonResponse));
            out.flush();
            out.close();
            return;
        }
        chain.doFilter(request, response);
    }
}
项目:digag-server    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain) throws ServletException, IOException {

    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(tokenHead)) {
        final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
        String account = jwtTokenUtil.getUsernameFromToken(authToken);

        logger.info("checking authentication " + account);

        if (account != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            // 如果我们足够相信token中的数据,也就是我们足够相信签名token的secret的机制足够好
            // 这种情况下,我们可以不用再查询数据库,而直接采用token中的数据
            // 本例中,我们还是通过Spring Security的 @UserDetailsService 进行了数据查询
            // 但简单验证的话,你可以采用直接验证token是否合法来避免昂贵的数据查询
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(account);

            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                        request));
                logger.info("authenticated user " + account + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }

    chain.doFilter(request, response);
}
项目:generator-spring-rest-jwt    文件:_JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication for user " + username);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:bxbot-ui-server    文件:JwtAuthenticationFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    try {

        // Extract token after Bearer prefix if present
        String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) {
            authorizationHeader = authorizationHeader.substring(BEARER_PREFIX_LENGTH);
        }

        // Might be null if client does not have a token yet
        if (authorizationHeader != null) {

            final Claims claims = jwtUtils.validateTokenAndGetClaims(authorizationHeader);
            final String username = jwtUtils.getUsernameFromTokenClaims(claims);
            LOG.info(() -> "Username in JWT: " + username);

            if (SecurityContextHolder.getContext().getAuthentication() == null) {

                // It is not compulsory to load the User details from the database.
                // We can just use the information in the token claims - this saves a repo lookup.
                //
                // final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // if (userDetails != null && !(userDetails.getUsername().equals(username))) {
                //    final String errorMsg = "Username is token not found in User repository! Token username: " + username;
                //    throw new JwtAuthenticationException(errorMsg);
                // }

                LOG.info(() -> "JWT is valid");

                // final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                //        userDetails, null, userDetails.getAuthorities());
                final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, jwtUtils.getRolesFromTokenClaims(claims));

                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);

                LOG.info(() -> "Authenticated User: " + username + " has been set in Spring SecurityContext.");
            }
        }

        chain.doFilter(request, response);

    } catch (Exception e) {
        LOG.error("JWT Authentication failure! Details: " + e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
项目:parkingcloud    文件:JwtOncePerRequestFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String token = request.getHeader(tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    if (!tokenUtil.parseToken(token)){
        return;
    }
    String username = tokenUtil.getUsername();

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (!tokenUtil.isExpired()) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    filterChain.doFilter(request, response);
}
项目:bf-editor    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(tokenHead)) {
        final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        logger.info("checking authentication " + 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 + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }

    chain.doFilter(request, response);
}
项目:microservices-sample-project    文件:CommonAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

    String authToken = request.getHeader(this.tokenHeader);

    if (!StringUtils.isEmpty(authToken) && SecurityContextHolder.getContext().getAuthentication() == null) {

        try{

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", authToken);
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

            HttpEntity<String> entity = new HttpEntity<String>("", headers);

            ResponseEntity<String> responseEntity = 
                    restTemplate.exchange(
                            "http://AUTH-SERVICE/auth/current"
                            , HttpMethod.POST
                            , entity
                            , String.class);

            String jsonUserDetails = responseEntity.getBody();
            UserDetails userDetails = prepareUserDetails(jsonUserDetails);

            if (userDetails != null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        }catch(Exception e){
            logger.error(e.getMessage());
        }

    }

    chain.doFilter(request, response);
}
项目:pokemon    文件:CommonAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

    String authToken = request.getHeader(this.tokenHeader);

    if (!StringUtils.isEmpty(authToken) && SecurityContextHolder.getContext().getAuthentication() == null) {

        try{

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", authToken);
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

            HttpEntity<String> entity = new HttpEntity<String>("", headers);

            ResponseEntity<String> responseEntity = 
                    restTemplate.exchange(
                            "http://AUTH-SERVICE/auth/current"
                            , HttpMethod.POST
                            , entity
                            , String.class);

            String jsonUserDetails = responseEntity.getBody();
            UserDetails userDetails = prepareUserDetails(jsonUserDetails);

            if (userDetails != null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        }catch(Exception e){
            logger.error(e.getMessage());
        }

    }

    chain.doFilter(request, response);
}
项目:spring-boot-start-current    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response ,
                                  FilterChain chain ) throws ServletException, IOException {
    final String authToken = this.extractAuthTokenFromRequest( request , this.tokenHeader );
    final String username  = jwtTokenUtil.getUsernameFromToken( authToken );

    LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , 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() );

            ThreadContext.put( USER_ID , String.valueOf( ( ( BasicJwtUser ) userDetails ).getId() ) );
            ThreadContext.put( USER_NAME , username );

            authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) );

            LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );

            LogUtils.getLogger().debug( "该 " + username + "用户已认证, 设置安全上下文" );

            SecurityContextHolder.getContext().setAuthentication( authentication );
        }
    }
    chain.doFilter( request , response );
    ThreadContext.clearAll();
}
项目:nifi-registry    文件:KerberosSpnegoIdentityProvider.java   
@Autowired
public KerberosSpnegoIdentityProvider(
        @Nullable  KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider,
        NiFiRegistryProperties properties) {
    this.kerberosServiceAuthenticationProvider = kerberosServiceAuthenticationProvider;
    authenticationDetailsSource = new WebAuthenticationDetailsSource();

    final String expirationFromProperties = properties.getKerberosSpnegoAuthenticationExpiration();
    if (expirationFromProperties != null) {
        long expiration = FormatUtils.getTimeDuration(expirationFromProperties, TimeUnit.MILLISECONDS);
    }
}
项目:tour-of-heros-api-security-zerhusen    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);

    if(authToken != null && authToken.startsWith("Bearer ")) {
        authToken = authToken.substring(7);
    }

    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication für user " + username);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:Integrate    文件:JwtAuthenticationTokenFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getParameter(this.tokenHeader);
    String userAppname = request.getParameter(this.appName);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String ybid = jwtTokenUtil.getYBidFromTocken(authToken);
    String appname = jwtTokenUtil.getAppnameFromTocken(authToken);

    logger.info("checking authentication for user " + ybid);

    if (ybid != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(ybid);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + ybid + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
项目:LushX    文件:JWTAuthenticationFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String auth_token = request.getHeader(this.token_header);
    final String auth_token_start = "Bearer ";
    if (StringUtils.isNotEmpty(auth_token) && auth_token.startsWith(auth_token_start)) {
        auth_token = auth_token.substring(auth_token_start.length());
    } else {
        // 不按规范,不允许通过验证
        auth_token = null;
    }
    String username = jwtUtils.getUsernameFromToken(auth_token);
    logger.info(String.format("Checking authentication for user %s.", username));

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        // UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        UserDetails userDetails = jwtUtils.getUserFromToken(auth_token);
        logger.info(userDetails.getUsername());
        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtUtils.validateToken(auth_token, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info(String.format("Authenticated user %s, setting security context", username));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    filterChain.doFilter(request, response);

}
项目:queue-ticket-api    文件:JwtAuthenticationTokenFilter.java   
private void doAuthentication(HttpServletRequest request, String authToken, String username) {
    if (username != null && securityContextHolderService.getAuthentication() == null) {
        UserDetails userDetails = this.userServiceDetail.loadUserByUsername(username);
        if (jwtTokenService.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            securityContextHolderService.setAuthentication(authentication);
        }
    }
}
项目:oma-riista-web    文件:OneTimePasswordFilterConfigurer.java   
@Override
public void configure(HttpSecurity http) {
    authFilter.setAuthenticationDetailsSource(new WebAuthenticationDetailsSource());
    authFilter.setApplicationEventPublisher(
            Objects.requireNonNull(http.getSharedObject(ApplicationContext.class)));
    authFilter.setAuthenticationManager(
            Objects.requireNonNull(http.getSharedObject(AuthenticationManager.class)));
    authFilter.setSessionAuthenticationStrategy(
            Objects.requireNonNull(http.getSharedObject(SessionAuthenticationStrategy.class)));
    authFilter.setRememberMeServices(
            Objects.requireNonNull(http.getSharedObject(RememberMeServices.class)));

    http.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class);
}
项目:stateless-rest-jwtcookie-demo    文件:ApiAuth.java   
public void restoreSecurityContext(HttpServletRequest request) {
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        String authToken = getRequestToken(request);
        if (authToken != null) {
            Claims tokenClaims = extractTokenClaims(authToken);
            String username = tokenClaims.getSubject();
            if (username != null) {
                UserAuth userAuth = null;

                try {
                    userAuth = (UserAuth) userDetailsService.loadUserByUsername(username);
                } catch (UsernameNotFoundException e) {
                    LOG.warn(String.format(">>> bad user token, username [%s] not found", username));
                }

                if (userAuth != null) {
                    String userId = tokenClaims.get("userId", String.class);
                    if (userId != null && userId.equals(Long.toString(userAuth.getId()))) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userAuth, null, userAuth.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);

                    } else {
                        LOG.warn(String.format(">>> bad user token, username [%s] not related to userId [%s]", username, userId));
                    }
                }
            }
        }
    }
}