首页 > 解决方案 > 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");
    }

}

标签: javaspring-security

解决方案


在您的 /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";
 }

推荐阅读