JwtRequestFilter无法从标头读取Jwt令牌,将“授权”标头值读取为空

时间:2020-10-21 02:35:47

标签: reactjs spring axios jwt

我正在使用React和Spring Boot。我正在使用axios发出我的api请求。 当我尝试向后端服务器发出api请求时,我的过滤器正在将标头值读取为null。

在我的反应方面,我正在通过登录表单进行身份验证,将令牌存储在localStorage中,然后当我使用componentDidMount调用敏感的api路由时,我认为我正确地将令牌作为Bearer + $ {token}传递。

这是我的明显错误。...

2020-10-20 22:23:12.064  WARN 1176 --- [nio-8080-exec-4] c.p.backend.Security.JwtRequestFilter    : JWT Token does not begin with Bearer String

这是我的代码。

处理登录逻辑的Login.js

onSubmit(e){

    e.preventDefault();
    const user = {
        username : this.state.username,
        password : this.state.password,
    }
    axios.post('http://localhost:8080/authenticate', user )

        .then( response =>{
            localStorage.setItem('token',response.data.token)
            console.log("token: ", localStorage.token);
        })
        .catch( (e) => {
            console.log(e);
        })
}

发出api请求的我的Portfolio.js组件

componentDidMount(){
const api = 'http://localhost:8080/api/getAssets';
const token = localStorage.get("token");
axios.get(api, { headers: {"Authorization" : "Bearer "+${token}} })
.then(res =>{
    this.setState({
            cash: res.data.cash,
            totalMarketValue: res.data.totalMarketValue,
            userStocks : res.data.stockInformation,
    })
    console.log(res.data);
})
.catch(err =>{console.log(err)}
)

}

我的Spring Boot jwtRequestFilter.java

@Component public class JwtRequestFilter extends OncePerRequestFilter {

@Autowired
private JwtUserDetailsService jwtUserDetailsService;

@Autowired
private JwtTokenUtil jwtTokenUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    final String requestTokenHeader = request.getHeader("Authorization");

    String username = null;
    String jwtToken = null;
    
    // JWT Token is in the form "Bearer token". Remove Bearer word and get
    // only the Token
    
    if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
        jwtToken = requestTokenHeader.substring(7);
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
        } catch (IllegalArgumentException e) {
            System.out.println("Unable to get JWT Token");
        } catch (ExpiredJwtException e) {
            System.out.println("JWT Token has expired");
        }
    } else {
        System.out.println( requestTokenHeader);
        logger.warn("JWT Token does not begin with Bearer String");
    }

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

        UserDetails userDetails = this.jwtUserDetailsService.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);
}

}

0 个答案:

没有答案