Spring Security错误403处理:未经授权的登录页面,授权用户的403错误

时间:2020-11-03 08:06:11

标签: java spring-security

我在处理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实现,我想从安全上下文检查用户,如果用户未登录-执行与重定向到禁止页面不同的操作,但是在这种情况下,身份验证始终为null,因为此错误记录了用户不幸的是该页面已注销

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");
    }

}

3 个答案:

答案 0 :(得分:1)

在/ errors /拒绝访问的映射上,检查 JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE cookie。如果它们为null,则表示用户没有成功登录才能获取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";
 }

答案 1 :(得分:0)

在您的安全配置文件中,我认为您可能需要添加不需要或不需要身份验证的应用程序的URL。

        @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // @formatter:off
        http
        .csrf().disable()
        .authorizeRequests() 
        .antMatchers("/login*",""
                + "/signin/**",""
                + "/signup/**",""
                + "/api/v1/products/**",""
                + "/api/v1/addproduct/**",""
                + "/api/v1/addCategory/**"
                ).permitAll()
        .anyRequest().authenticated()
//        .and() 
//        .formLogin().loginPage("/login").permitAll()
        .and()
        .logout();
    } // @formatter:on

答案 2 :(得分:0)

最后,我在Spring Security自定义过滤器中实现了此功能