如果启用了Spring Security RESTAPI不工作

qnakjoqk  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(363)
@SpringBootApplication()
@ComponentScan( basePackageClasses = {Implementation.class,ApiController.class})
public class ServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }

}

Spring 安全

@Configuration
@EnableWebSecurity
public class ApiController extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                csrf().disable()
                .antMatcher("/b/**")
                .addFilterAfter(new TokenFilter(), BasicAuthenticationFilter.class)
                .authorizeRequests().anyRequest().permitAll();
    }
}

令牌筛选器进行身份验证

public class TokenFilter extends OncePerRequestFilter
{

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
    {
        if( ! isTokenValid(request))
        {
            response.setStatus(401);
        }
    }

    private boolean isTokenValid(HttpServletRequest request)
    {
        return true;
    }
}

应用程序编程接口

@RestController
@RequestMapping(path = "/b")
public class Implementation
{

    @GetMapping(path = "/freeze")
    @ResponseBody
    public String freezeAMovieSlot( )
    {
        return "HI";
    }

如果我禁用spring security,我会收到hi响应,但对于上述代码,hi不会在响应中收到。。回复代码是200,我错过了!!!!

dpiehjr4

dpiehjr41#

添加后

filterChain.doFilter(request, response);

在tokenfilter类中的dofilterinternal方法中,它起作用。
这可能是因为过滤器掉在了中间,因为我没有用链子锁住它

相关问题