java - Spring安全错误403处理:未经授权的登录页面,授权用户的403错误
问题描述
我有以下 403 错误处理问题。这是我的配置:
我的 spring-security.xml 的一部分
<sec:http auto-config="true" use-expressions="true" entry-point-ref="ep403" disable-url-rewriting="true">
<sec:form-login login-page="/login"
login-processing-url="/login"
username-parameter="email"
password-parameter="password"
/>
<sec:access-denied-handler error-page="/errors/access-denied"/>
<sec:logout invalidate-session="true" delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
logout-success-url="/login"/>
<sec:session-management session-fixation-protection="newSession"/>
</sec:http>
<bean id="ep403" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
如果登录/未经授权的用户进入链接而无权查看 url - 如果已经登录,他将被重定向到 403 错误页面并从系统注销。我需要允许我将登录用户重定向到 403 页面并注销的解决方案,但是对于未经授权的用户我想看到登录页面而不是 403 错误,你知道有机会实现这个目标吗?
我尝试使用自己的 AuthenticationEntryPoint 实现,我想从安全上下文检查用户,如果它没有登录 - 执行与重定向到禁止页面不同的操作,但在这种情况下身份验证始终为空,因为不幸的是,此错误页面上的登录用户是已经登出
public class AccessDeniedEntryPoint implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException arg2) throws IOException, ServletException {
Authenticationauthentication = SecurityContextHolder.getContext().getAuthentication();
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
}
解决方案
在您的 /errors/access-denied 映射检查JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE cookie。如果它们为空,则意味着用户没有成功登录以获得 cookie,因此将他重定向到登录,如果没有让他看到拒绝访问页面。
@RequestMapping(value="/errors/access-denied")
public String error(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("JSESSIONID") ||
cookie.getName().equals("SPRING_SECURITY_REMEMBER_ME_COOKIE")) {
return "access-denied";
}
}
return "login";
}
推荐阅读
- java - 如何从我放入数组列表的对象中检索信息
- python-3.x - 数据框问题:在 df 中输入新列并创建方程式以获取百分比
- html - 如何在标题行末尾以中心对齐和潜文本对齐的方式编写标题?
- firebase - 为什么我使用 EmailisVerifiyed bool 得到 stackoverflow 错误?
- c# - 如何在 Xamarin 表单中使用构造函数注入
- postgresql - 目标中具有新架构名称的 RDS 架构复制
- typescript - 使用 Redux Observable 合并映射后无法传播值
- google-apps-script - Google Apps 脚本每日计划触发器失败
- html - CSS:具有最小/最大宽度的正方形并换行
- python - Python/Pandas:如何修改数据框列中的数据并将转换列表附加到新列