Spring Security 6 Пользовательский фильтр не применяется к конкретному шаблону URL -адреса вJAVA

Программисты JAVA общаются здесь
Anonymous
Spring Security 6 Пользовательский фильтр не применяется к конкретному шаблону URL -адреса в

Сообщение Anonymous »

У меня есть класс конфигурации, в котором я хочу, чтобы пользовательские фильтру Secfilters были применены только к конкретным шаблонам URL (/API/V1/,/API/* и т. Д.). У меня тоже есть отдельный боб для входа в систему. Но этот пользовательский фильтр применяется ко всем URL -адресам, включая /вход в систему и не придерживаться только указанной шаблона. Пока - код. < /P>
@Configuration
@EnableWebSecurity
@EnableMethodSecurity //Required for @PreAuthorize
public class SLWebConfig{

@Bean
@Order(1)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{

http.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests((authz) -> authz

.requestMatchers("/api/v1/").permitAll() //allowing to accessed with authentication
.requestMatchers("/api/*").authenticated() //securing only the client APIs
.requestMatchers("*/users/{userId}/**").access(new WebExpressionAuthorizationManager("@userSecurity.hasUserId(authentication,#userId)"))
);
http.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilterBefore(new SecFilters(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}

@Bean
@Order(2)
public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception{
http
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
.formLogin(form -> form
.loginPage("/login").permitAll()
).csrf(AbstractHttpConfigurer::disable);
return http.build();

}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}

Below is my custom Filter

@Component
public class SecFilters extends GenericFilterBean{

private static TokenExtractor tokenExtractor = new BearerTokenExtractor();

private LicenseService licenseService;
@Autowired
public void setLicenseService(LicenseService licenseService) {
this.licenseService = licenseService;
}

private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("i18n.messages", new Locale("en"));

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

try
{
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;

//checking the licence of the server
if(licenseService.isLicenseExpired()) {
httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}

String requestURL = httpServletRequest.getRequestURI();
if(System.getenv("SERVER_LOG_LEVEL").equals("INFO")){
SLLogger.logInfo(httpServletRequest.getRequestURL().toString());
}

//request from UI client : Place holder
if (null != httpServletRequest.getHeader("www-Authorization")) {

}

String header = httpServletRequest.getHeader("Authorization");

// Get the token from the request

Authentication authentication = (Authentication) httpServletRequest.getUserPrincipal();
String token = null;
if(authentication != null)
token = authentication.getPrincipal().toString();

try {

chain.doFilter(request, response);

}catch (IndexOutOfBoundsException e)
{
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
throw e;
}
catch (HttpClientErrorException e) {

throw e;
}
}

@Bean
public FilterRegistrationBean clientRequestFilterRegistrationBean(SecFilters OAuthRequestFilter1){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(OAuthRequestFilter1);
registrationBean.setEnabled(false);
return registrationBean;
}
}
< /code>
Пожалуйста, дайте мне знать, как я могу иметь отдельные правила для разных URL. Это перестало работать после того, как я перешел на Spring 6 и Spring Boot 3.
заранее. < /P>

Подробнее здесь: https://stackoverflow.com/questions/795 ... pattern-in

Вернуться в «JAVA»