Spring Security Sping Boot 使用多个JWT的多个路由

zu0ti5jz  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(156)

我需要为我的端点实现Spring JWT安全性。我有2条路线- 1为内部和外部第二。我试图添加下面的代码,但我的两个过滤器都在执行任何请求。我可以根据URL在过滤器中添加一个逻辑。但我觉得这不是正确的方法。请让我知道什么是正确的方法,以及如何解决它?

http
   .csrf().disable()
   .authorizeRequests()
   .antMatchers("/internal/**") 
       .authenticated()
   .and()
   .addFilterBefore(jwtAuthenticationInternalFilter(), BasicAuthenticationFilter.class)
   .authorizeRequests()
   .antMatchers("/external/**")
   .authenticated()
   .and()
   .addFilterBefore(jwtAuthenticationExternalFilter(), BasicAuthenticationFilter.class);


public class ExternalAuthenticationFilter extends OncePerRequestFilter {

    @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("Its hitting here  - External");//GET THE Information and build Authentication object..

        //  SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }

}

public class InternalAuthenticationFilter extends OncePerRequestFilter {

    @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("Its hitting here - Internal");//GET THE Information and build Authentication object..

        //  SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }

}

字符串
内部和外部代码都在为任何请求执行。sample request /internal/abc,
/external/xyz ..这两种情况下,两个过滤器都被调用。
请建议

kfgdxczn

kfgdxczn1#

您可以将安全设置分为两个不同的配置类,并使用例如@Order(1)@Order(2)注解。一个配置将处理/internal端点,另一个配置将处理/external端点。在configure(HttpSecurity http)方法中,首先指定要配置的端点,然后应用设置。
参见下面的一个配置示例,第二个配置将是类似的:

@EnableWebSecurity
    @Order(1)
    public class ExternalEndpointsSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/internal/**")
                .authorizeRequests()
                .authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationInternalFilter(), BasicAuthenticationFilter.class)
        }
    }

字符串

相关问题