Sam*_*nia 6 rest spring spring-security
我有一个公开 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");
}
}
Run Code Online (Sandbox Code Playgroud)
在安全配置类中(例如WebSecurityConfig):
自动装配 bean:
@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,
Run Code Online (Sandbox Code Playgroud)
指定处理程序:
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,
Run Code Online (Sandbox Code Playgroud)
提示:
401code,让前端处理。401响应,CommenceEntryPoint.commence()只需使用response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");而不是response.sendRedirect().我通过将以下元素添加到节点下的 Spring Security XML 中解决了这个问题http:
<security:access-denied-handler error-page="/#/login" />
<security:session-management invalid-session-url="/#/login" session-fixation-protection="changeSessionId" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6486 次 |
| 最近记录: |