春季启动:为什么要使用OncePerRequestFilter?

时间:2020-03-31 09:49:25

标签: java spring spring-boot

我有一个名为JwtTokenAuthorizationOncePerRequestFilter的类,其中它扩展了OncePerRequestFilter

但是,登录后使用网络应用程序后出现问题

我总是得到“ JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING”

请参见下面的代码:

package com.sbc.cpex.security.jwt;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import io.jsonwebtoken.ExpiredJwtException;

@Component
public class JwtTokenAuthorizationOncePerRequestFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserDetailsService jwtInMemoryUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.http.request.header}")
    private String tokenHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        logger.debug("Authentication Request For '{}'", request.getRequestURL());

        final String requestTokenHeader = request.getHeader(this.tokenHeader);

        String username = null;
        String jwtToken = null;
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                logger.error("JWT_TOKEN_UNABLE_TO_GET_USERNAME", e);
            } catch (ExpiredJwtException e) {
                logger.warn("JWT_TOKEN_EXPIRED", e);
            }
        } else {
            logger.warn("JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING");
        }

        logger.debug("JWT_TOKEN_USERNAME_VALUE '{}'", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

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

            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        chain.doFilter(request, response);
    }
}

我是否可以在登录时触发此类?而不是在接受其他请求时

TIA

4 个答案:

答案 0 :(得分:0)

好吧,如果有人不发送承载令牌,就会收到“警告”,因为您有以下一行:

 logger.warn("JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING");

我认为您可能会保护应用程序中的所有URL,因此需要为每个URL使用JWTFilter。

答案 1 :(得分:0)

记录器仅在登录期间发出警告,因为请求URL尚未包含承载令牌。如果您为带有令牌的令牌和会话登录存储时生成的令牌设置会话存储,则成功的URL调用将不再显示此警告消息

答案 2 :(得分:0)

您没有在“ Authorization”标头上传递令牌,或者您正在传递的此令牌不是以Bearer开头。考虑将create generate令牌放入这些方法中

答案 3 :(得分:0)

因为String username = null; 并且没有任何地方为用户名分配来自请求的值。 您需要从 HttpServletRequest 请求中获取 JSONObject 并解析它以获取用户名。