我需要为我的终点实现Spring JWT安全性。我有2条路线 - 一条用于内部,第二条用于外部。我尝试添加下面的代码,但我的过滤器都针对任何请求执行.. 我可以根据网址在过滤器中添加一个逻辑..但我觉得这不是正确的方法。请让我知道什么是正确的方法以及如何解决它?
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);
}
}
内部和外部代码都针对任何请求执行。
样品申请
/内部/ ABC,
/ external / xyz ..这两个过滤器都被调用..
请建议
答案 0 :(得分:0)
您可以将安全设置拆分为两个不同的配置类,并使用例如@Order(1)
和@Order(2)
注释。一个配置将处理/internal
端点和一个/external
端点。在configure(HttpSecurity http)
方法中,首先指定您要配置的端点,然后应用您的设置。
参见下面一个配置的示例,第二个配置将是anological:
@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)
}
}