>我有一个使用安全性的 Spring 启动应用程序。这个应用程序使用MVC来显示一些页面,也使用一些休息接口来更新/获取对象。
现在,我在未登录的情况下发出的每个请求都会被重定向到 /login 页面。
当我尝试从网络浏览器访问时,这是按预期工作的。但是我希望当我尝试从页面访问某些特定路径时,应用程序的反应会有所不同,例如"/api/customers"。
如果我尝试访问该路径,我想删除HTTP 403错误,而不是重定向到登录页面。
这是我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers()
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN);
http.authorizeRequests()
.antMatchers("/js/**", "/img/**")
.permitAll()
.antMatchers("/**").authenticated()
.and()
.csrf().disable()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logged-out")
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied")
;
}
这可能吗?
您可以创建自定义 AuthenticationEntryPoint:
https://docs.spring.io/spring-security/site/docs/4.0.4.RELEASE/reference/htmlsingle/#auth-entry-point
如果用户请求 保护 HTTP 资源,但它们未经过身份验证。一个适当的 AuthenticationException 或 AccessDeniedException 将由 安全拦截器进一步向下调用堆栈,触发 在入口点开始方法。这完成了呈现的工作 对用户的适当响应,以便可以开始身份验证。
@Component
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex)
throws IOException, ServletException {
boolean somePath = request.getServletPath().equals("/somePath");
if(somePath){
response.sendError(SC_FORBIDDEN, "Access Denied");
}
else{
response.sendRedirect("/login");
}
}
}
并将其注册到框架中:
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
Spring Security 有一个DelegatingAuthenticationEntryPoint
,允许根据RequestMatcher
评估选择具体的AuthenticationEntryPoint
。
https://docs.spring.io/spring-security/site/docs/5.7.x/api/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPoint.html