gpt4 book ai didi

spring - 如何避免使用 Spring Security 重定向到某些 URL 的登录表单?

转载 作者:行者123 更新时间:2023-12-03 20:17:56 30 4
gpt4 key购买 nike

这是我的 webapp 的 Spring Security 配置

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", LOGIN, "/webjars/**").permitAll()
.antMatchers(CONFIGURATION).hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
.antMatchers("/api/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
.and()
.formLogin()
.loginPage(LOGIN)
.and()
.addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class);
}

目前服务器正在重定向到 LOGIN页面每个没有正确凭据的请求。

我想重定向到 LOGIN页面仅将未经授权的请求发送至 CONFIGURATION , 而未经授权的请求到 /api/**应该回答 403。

实现这一目标的好方法是什么?

最佳答案

我使用 AuthenticationEntryPoint 解决了我的问题:

http
.authorizeRequests()
.antMatchers(LOGIN).permitAll()
.antMatchers("/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey())
.and()
.addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(unauthenticatedRequestHandler);

@Bean
UnauthenticatedRequestHandler unauthenticatedRequestHandler() {
return new UnauthenticatedRequestHandler();
}

static class UnauthenticatedRequestHandler implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
if (request.getServletPath().startsWith("/api/")) {
response.setStatus(403);
} else {
response.sendRedirect(LOGIN);
}
}
}

关于spring - 如何避免使用 Spring Security 重定向到某些 URL 的登录表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031048/

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