首页 > 解决方案 > 从标头获取访问令牌

问题描述

我已经创建了一个 oauth Bearer 令牌创建者,但是当我检查有效性时,我需要授权标头来提取令牌,我在下面编写了代码,但是 auth 标头总是为空,这是什么问题?

@Component
public class JwtTokenFilter extends OncePerRequestFilter {


    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    @NotNull HttpServletResponse httpServletResponse,
                                    @NotNull FilterChain filterChain) throws ServletException, IOException {

        /**
         * We are parsing our token in two pieces and we process the second
         * "Bearer hvs231asas2355"
         */
        final String authHeader = httpServletRequest.getHeader("Authorization");  // this part always gets null
        String afId = null;
        String token = null;



        if (authHeader != null && authHeader.contains("Bearer")) {
            token = authHeader.substring(7);

            afId = tokenManager.getUsernameToken(token);


        }

        if (afId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (tokenManager.tokenValidate(token)) {
                AnonymousAuthenticationToken anonymousAuthenticationToken=new AnonymousAuthenticationToken(token,null,new ArrayList<>());
                authenticationManager.authenticate(anonymousAuthenticationToken);
                anonymousAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                SecurityContextHolder.getContext().setAuthentication(anonymousAuthenticationToken);


            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

注意:我确信我从邮递员那里发送了标头中的令牌,但不知何故它无法从 httpServlet 获取。

标签: javaspringspring-bootspring-securityjwt

解决方案


推荐阅读