英文:
Exclude authentication to pass by filter In spring security
问题
我想要从过滤器中排除一个 URL。我添加了允许所有,但每次我进行身份验证请求时,它都会通过过滤器。顺便说一下,当我移除过滤器时,它会进行身份验证。我的目标是从通过过滤器的一些 URL 中排除。这是我的配置和过滤器的代码:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/AuthentificationController/**").permitAll()
.antMatchers("/swagger-ui.html").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterAfter(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
这是我的过滤器代码:
package tn.afriquecarglass.gestionstock.filters;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import tn.afriquecarglass.gestionstock.util.JwtUtil;
import tn.afriquecarglass.gestionstock.util.MyUserDetailsService;
@Component
public class JwtRequestFilter extends OncePerRequestFilter{
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if(authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);
if(jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
filterChain.doFilter(request, response);
}
}
}
英文:
I want to exclude an url from passing by the filter. I added the permit all but every time I make an authentication request it passes by the filter. By the way, when I remove the filter it makes an authentication. The goal for me is excluding some urls from passing through the filter. This is my config and my filter 's code :
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/AuthentificationController/**").permitAll()
.antMatchers("/swagger-ui.html").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterAfter(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
This is my filter's code:
package tn.afriquecarglass.gestionstock.filters;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import tn.afriquecarglass.gestionstock.util.JwtUtil;
import tn.afriquecarglass.gestionstock.util.MyUserDetailsService;
@Component
public class JwtRequestFilter extends OncePerRequestFilter{
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if(authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if(username!=null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);
if(jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
filterChain.doFilter(request, response);
}
}
}
答案1
得分: 1
以下是您要翻译的内容:
您可以在自定义过滤器中提供逻辑,以便在请求的路径与您要绕过的路径列表匹配时跳过该逻辑,并将处理委托给下一个过滤器。
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
String reqPath = request.getRequestURI();
// 如果匹配,则继续到下一个过滤器
if ("/path_to_skip".equals(reqPath)) {
filterChain.doFilter(request, response);
return;
}
// 其余逻辑部分
...
}
英文:
You can provide logic in your custom filter itself to be skipped if requested path matches your list of paths you want to be bypassed and delegate to the next filter
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
String reqPath = request.getRequestURI();
// If not matched then continue to the next filter
if ("/path_to_skipp".equals(reqPath )) {
filterChain.doFilter(request, response);
return;
}
// rest of your logic
...
}
答案2
得分: 0
如果您想要完全从Spring Security的filterChain中排除URL,只需重写
configure(WebSecurity web)
方法。
示例:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/yourUrls/**");
}
}
英文:
If you want to completely exclude the URL from Spring Security's filterChain, simply override the
configure(WebSecurity web)
method.
Example:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/yourUrls/**");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论