gpt4 book ai didi

java - Spring Security-如何在 CustomTokenAuthenticationFilter 中指定过滤器处理 url

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:16 24 4
gpt4 key购买 nike

我正在尝试使用 token 保护我的 Spring Rest API,这是我的自定义过滤器

public class CustomTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

private static final Logger logger = LoggerFactory.getLogger(CustomTokenAuthenticationFilter.class);

public CustomTokenAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
setAuthenticationManager(new NoOpAuthenticationManager());
setAuthenticationSuccessHandler(new TokenSimpleUrlAuthenticationSuccessHandler());
}


public final String HEADER_SECURITY_TOKEN = "X-CustomToken";

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String token = request.getHeader(HEADER_SECURITY_TOKEN);
logger.info("token found:"+token);
AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token);
if(userAuthenticationToken == null || userAuthenticationToken.getPrincipal().equals("guest")) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
return userAuthenticationToken;
}


/**
* authenticate the user based on token
* @return
*/
private AbstractAuthenticationToken authUserByToken(String token) {
if(token==null) {
return null;
}
AbstractAuthenticationToken authToken = new MyToken(token);
try {
return authToken;
} catch (Exception e) {
logger.error("Authenticate user by token error: ", e);
}
return authToken;
}


@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
super.doFilter(req, res, chain);
}

}

这是我的配置方式

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
protected AbstractAuthenticationProcessingFilter getFilter() {
return new CustomTokenAuthenticationFilter("/api/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.addFilterBefore(getFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable();
}
}

如果你看一下 getFilter(),我已经传递了“/api/*”作为过滤器处理 url,但我想使用 HttpSecurity 对象配置这些 url,如下

http.authorizeRequests().antMatchers("/", "/rome").permitAll()
.antMatchers("/api/admin", "/api/newUser").access("hasRole('ADMIN')")
.antMatchers("/api/db").access("hasRole('ADMIN') or hasRole('DBA')")

我看到的问题是,自定义过滤器需要一个字符串作为“过滤器处理 url”,但我不想指定任何内容。该信息应该通过 antMatchers 等配置 HttpSecurity 对象来传递。

这真的可能吗?如果是,我怎样才能实现这一目标?

最佳答案

我使用了OncePerRequestFilter

public class MyAuthenticationFilter extends OncePerRequestFilter {

// private RequestMatcher requestMatcher;
private List<RequestMatcher> includedPathMatchers = new ArrayList<>();
private List<RequestMatcher> excludedPathMatchers = new ArrayList<>();

// implement getters and setters
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
// your filter implementation and security logics
}

}

您可以将此类视为普通 bean(使用@Autowired 等)。然后您只需在您的上下文中注册它并将其注入(inject)安全链中。

希望有帮助。

关于java - Spring Security-如何在 CustomTokenAuthenticationFilter 中指定过滤器处理 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com