我有一个暴露REST API的应用程序,并使用Spring Security进行保护。有没有办法自动将客户端(从服务器端)重定向到登录页面如果发送到我的服务器的请求导致401 - 未经授权?
对于基于spring-security
的spring-boot
应用程序。
定义处理程序bean:
@Component
public class CommenceEntryPoint implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = 565662170056829238L;
// invoked when user tries to access a secured REST resource without supplying any credentials,
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
// send a json object, with http code 401,
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
// redirect to login page, for non-ajax request,
response.sendRedirect("/login.html");
}
}
在安全配置类(例如WebSecurityConfig
)中:
自动化bean:
@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,
指定处理程序
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,
提示:
401
代码,并让前端处理它。
如果你想使用401
响应,在CommenceEntryPoint.commence()
只需使用response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
而不是response.sendRedirect()
。您可以通过在web.xml的error-page元素中指定异常或HTTP状态代码来指定应用程序处理异常或HTTP状态代码的方式
eq:vb.hm
<error-page>
<error-code>401</error-code>
<location>/login.html</location>
</error-page>
与处理页面未找到页面的其他HTTP状态代码即404相同。
我通过在http
节点下将以下元素添加到我的Spring Security XML来解决了这个问题:
<security:access-denied-handler error-page="/#/login" />
<security:session-management invalid-session-url="/#/login" session-fixation-protection="changeSessionId" />