如何使用Spring Security避免重定向到某个URL的登录表单?
这是我的webapp的Spring安全配置如何使用Spring Security避免重定向到某个URL的登录表单?,spring,spring-boot,spring-security,Spring,Spring Boot,Spring Security,这是我的webapp的Spring安全配置 @覆盖 受保护的无效配置(HttpSecurity http)引发异常{ http .授权请求() .antMatchers(“/”,LOGIN,“/webjars/**”).permitAll() .antMatchers(配置).hasAuthority(Authorities.AUTHORITY\u SOLMAN72\u EXPORT\u ENABLED.getKey()) .antMatchers(“/api/**”).hasAuthority
@覆盖
受保护的无效配置(HttpSecurity http)引发异常{
http
.授权请求()
.antMatchers(“/”,LOGIN,“/webjars/**”).permitAll()
.antMatchers(配置).hasAuthority(Authorities.AUTHORITY\u SOLMAN72\u EXPORT\u ENABLED.getKey())
.antMatchers(“/api/**”).hasAuthority(Authorities.AUTHORITY\u SOLMAN72\u EXPORT\u ENABLED.getKey())
.及()
.formLogin()
.LOGIN页面(登录)
.及()
.addFilterBefore(oAuth2ClientAuthenticationProcessingFilter,BasicAuthenticationFilter.class);
}
当前,服务器正在将每个没有正确凭据的请求重定向到登录
页面
我只想重定向到登录
页面,对配置
的未经授权的请求,而对/api/**
的未经授权的请求应回答403
实现这一点的好方法是什么?我使用
认证入口点解决了我的问题:
http
.授权请求()
.antMatchers(登录名).permitAll()
.antMatchers(“/**”).hasAuthority(Authorities.AUTHORITY\u SOLMAN72\u EXPORT\u ENABLED.getKey())
.及()
.addFilterBefore(oAuth2ClientAuthenticationProcessingFilter,BasicAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(未经身份验证的RequestHandler);
@Bean
UnauthenticatedRequestHandler UnauthenticatedRequestHandler(){
返回新的未经身份验证的RequestHandler();
}
静态类UnauthenticatedRequestHandler实现AuthenticationEntryPoint{
@凌驾
public void start(HttpServletRequest请求、HttpServletResponse响应、AuthenticationException authException)引发IOException{
if(request.getServletPath().startsWith(“/api/”){
答复:setStatus(403);
}否则{
sendRedirect(登录);
}
}
}
您可以使用:
一种AuthenticationEntryPoint
,它根据请求匹配者的评估选择一个具体的AuthenticationEntryPoint
使用for/api/**
和作为默认入口点
@Bean
public DelegatingAuthenticationEntryPoint DelegatingAuthenticationEntryPoint(){
LinkedHashMap入口点=新建LinkedHashMap();
put(新的AntPathRequestMatcher(“/api/**”),新的Http403ForbiddenEntryPoint();
DelegatingAuthenticationEntryPoint defaultEntryPoint=新的DelegatingAuthenticationEntryPoint(entryPoints);
setDefaultEntryPoint(新的登录名LauthenticationEntryPoint(登录名));
返回defaultEntryPoint;
}
我去实现dur的答案,但注意到有一个(可从各地获得)可以有效地用更少的依赖性代码完成同样的事情:
http.exceptionHandling()
.defaultAuthenticationEntryPointFor(new Http403ForbiddenEntryPoint(), new AntPathRequestMatcher("/api/**"));
此外,我注意到指定了任何defaultAuthenticationEntryPointFor()
默认情况下,FormLoginConfigurer
,OAuth2LoginConfigurer
,Saml2LoginConfigurer
,等等。在SecurityConfigurer.init()
期间,除非我们指定了一个,否则其中的第一个将成为默认入口点
这可能有用,也可能无用,但因为
FormLoginConfiguration
提供的AuthenticationEntryPoint
,OAuth2LoginConfiguration
,Saml2LoginConfiguration
等。包含头X-request-With:XMLHttpRequest
的请求,我们用defaultAuthenticationEntryPointFor()指定的入口点
最终将用于AJAX,而不管我们为请求匹配器参数指定了什么