JWTAuthenticationFilter

JWTAuthenticationFilter

我有

@Configuration
@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/v1/account/import").permitAll()
                .anyRequest().authenticated()
                .and()
            .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }


我希望所有用户都可以进入/api/v1/account/import而无需进行任何JWT令牌检查。对于所有其他端点,我希望在类JWTAuthenticationFilter中进行JWT令牌检查。我尝试了许多不同的方案,但都失败了。我总是去JWTAuthenticationFilter。如果我去JWTAuthenticationFilter,我不想去/api/v1/account/import

我的控制器:



@RestController
@RequestMapping(value = "/api/v1/account")
public class AccountController {

    private final AccountService accountService;

    public AccountController(final AccountService accountService) {
        this.accountService = accountService;
    }

    @PostMapping(path = "/import")
    @ResponseStatus(HttpStatus.ACCEPTED)
    public String importAccount(@Valid @RequestBody final ImportAccountDto importAccountDto) {
        return this.accountService.importAccount(importAccountDto);
    }


我的JWT过滤器:

public class JWTAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain filterChain) throws IOException, ServletException {

        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        final String token = request.getHeader("Authorization");

        final JJWTService jjwtService = new JJWTService();

        if (token == null || !jjwtService.parseJWTToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            filterChain.doFilter(req, res);
        }
    }


我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountIT {

    @Autowired
    MockMvc mockMvc;

    @Autowired
    private AccountRepository accountRepository;

    @Test
    public void importAccount() throws Exception {

        this.mockMvc.perform(post("/api/v1/account/import")
                .contentType(MediaType.APPLICATION_JSON)
                .content(toJson(importAccountDto)))
                .andExpect(status().isAccepted())
                .andReturn();
    }

最佳答案

尝试这个

if (!request.getRequestURI().contains("/api/v1/account/import")) {
    final JJWTService jjwtService = new JJWTService();

    if (token == null || !jjwtService.parseJWTToken(token)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        filterChain.doFilter(req, res);
    }
}

09-08 08:28