以下是我的 Spring Security 配置示例。
我希望所有 /api
返回 HTTP 401 代码,而不是将 302 重定向到登录页面。
此外,我想保留旧网页的重定向功能。
<security:http auto-config='true' use-expressions="true" >
<security:intercept-url pattern="/api*" access="hasRole('USER')" />
<security:intercept-url pattern="/oldweb*" access="hasRole('USER')" />
<security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home"/>
</security:http>
最佳答案
我找到了更简单的解决方案。
在 Spring Boot 和 Java 配置中,除了默认入口点之外,您只需要注册其他入口点。由于所有休息服务都驻留在“/api”命名空间中,因此您可以使用 AntPathRequestMatcher("/api/**")
来匹配必要的请求。
所以,最终的解决方案是:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
//Actually Spring already configures default AuthenticationEntryPoint - LoginUrlAuthenticationEntryPoint
//This one is REST-specific addition to default one, that is based on PathRequest
.defaultAuthenticationEntryPointFor(getRestAuthenticationEntryPoint(), new AntPathRequestMatcher("/api/**"));
}
private AuthenticationEntryPoint getRestAuthenticationEntryPoint() {
return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}
}
关于spring - 如何在 Spring Security 中为 REST API 调用返回 401?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358856/