我有一个应用程序公开REST API,并使用Spring安全保护。如果发送到我的服务器的请求导致401 - 未经授权,是否有方法可以自动将客户端(从服务器端)重定向到登录页面?春季安全:重定向到登录页面的情况下401
1
A
回答
0
我由http
节点下添加以下内容到我的春季安全XML解决了这个问题:
<security:access-denied-handler error-page="/#/login" />
<security:session-management invalid-session-url="/#/login" session-fixation-protection="changeSessionId" />
0
您可以指定你的应用程序通过web.xml中的错误页面元素将其指定
如处理异常或HTTP状态代码:web.xml中
<error-page>
<error-code>401</error-code>
<location>/login.html</location>
</error-page>
相同的方式,处理其他HTTP状态码404代表页面未找到页面。
0
对于spring-security
应用基于spring-boot
。
定义处理豆:
@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
):
的Autowire豆:
@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,
指定的处理程序:
个.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,
提示:
- 这仅适用于非Ajax请求,
- 对于Ajax请求,更好的回报
401
代码,并让前端处理。
如果要使用401
响应,请在CommenceEntryPoint.commence()
中使用response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
而不是response.sendRedirect()
。
相关问题
- 1. 春季安全始终是登录页面重定向
- 2. 春季安全登录页面?
- 3. 春季开机和春季安全总是重定向到登录
- 4. 春季安全返回401/403,而不是将用户重定向到登录页面
- 5. 春季安全Grails的登录重定向
- 6. 春季安全。不重定向下降一个拦截的URL后到登录页面
- 7. 登录页面将不能重定向到安全页面
- 8. 春季安全只显示登录页面的页眉
- 9. 春季安全登录/注销登录
- 10. 春季安全SAML:自己的登录页面而不是ADFS登录重定向
- 11. 春季安全自定义登录表单重定向到资源不可用
- 12. 在春季安全2.0.2如何重定向到登录后请求的网址
- 13. 春季安全重定向到登录表单与基于Java的配置
- 14. 春季安全重定向如果
- 15. 重定向注销春季安全
- 16. 春季安全不会重定向到主页
- 17. 春季安全会话过期时自动重定向到登录4.1
- 18. 在会话检查的某些情况下重定向到登录页面
- 19. 春季开机和弹簧安全多登录页面
- 20. 春季安全登录注销的URI
- 21. 抛出安全异常后,重定向到登录页面
- 22. 春季安全配置2种登录行为 - Ajax响应JSON和表单登录重定向新的一页
- 23. 弹簧安全3.1-重定向到具有上下文url的登录页面
- 24. 春季安全阿贾克斯登录
- 25. 春季安全只允许oauth登录
- 26. 春季安全角色访问,登录
- 27. 春季安全无形体登录
- 28. 春季安全预认证/登录
- 29. 春季安全和角js ajax登录
- 30. 春季安全 - 登录架构
有没有办法使用基于java/annotaion的配置来做到这一点? –