Spring Boot中的JWT令牌配置问题

我遇到的问题是,当我调用发帖请求时:localhost:8080/authenticate 我的应用程序的安全性表示需要和令牌。当请求被调用时,过滤器会遍历它,所以这不是故意的。现在,安全性在这是第一个请求时要求一个承载令牌,当然还不存在。我收到错误JWT Token does not begin with Bearer String

我的配置方法:

@Override
    protected void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/authenticate");
    }

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers("/authenticate").permitAll()
                .antMatchers("/**/private/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .addFilterBefore(jwtRequestFilter,usernamePasswordauthenticationFilter.class)
                .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint);
    }

我的过滤方法:

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

        final String requestTokenHeader = request.getHeader("Authorization");
        System.out.println("JWT Request: " + request.getRequesturi());
        System.out.println("JWT Contain: " + request.getRequesturi().contains("authenticate"));
        String username = null;
        String jwtToken = null;
        //Remove comment for second approach
        if (request.getRequesturi().contains("authenticate") == false) {
            System.out.println("Do Noting,Permit It");
            chain.doFilter(request,response);
        } else 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 {
            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);
    }

我的控制器类:

@RestController
@CrossOrigin
public class JwtAuthenticationController {

    @Autowired
    private Authenticationmanager authenticationmanager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @RequestMapping(value = "/authenticate",method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {

        authenticate(authenticationRequest.getusername(),authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService
                .loadUserByusername(authenticationRequest.getusername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ResponseEntity<?> saveUser(@RequestBody UserDTO user) throws Exception {
        return ResponseEntity.ok(userDetailsService.save(user));
    }

    private void authenticate(String username,String password) throws Exception {
        try {
            authenticationmanager.authenticate(new usernamePasswordauthenticationToken(username,password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED",e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS",e);
        }
    }
}

我希望程序能够正常工作,以便在我发送localhost:8080/authenticate请求时将没有过滤器,但是当我调用其他所有请求时,将有过滤器检查令牌是否存在。

先谢谢您。

SanG_Soul 回答:Spring Boot中的JWT令牌配置问题

重写方法configure(WebSecurity web)忽略/authenticate端点,以使其不包含在Spring Security过滤器链中,如下所示;

public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authenticate");                
}
本文链接:https://www.f2er.com/3159847.html

大家都在问