如何让Spring Security中的permitAll不在@Controller对象中抛出AuthenticationCredentialsNotFoundException?

ege*_*ari 6 authentication authorization controller exception spring-security

我有一个控制器有很多动作,它指定一个默认的类级别@PreAuthorize注释,但我想让任何人进入的一个动作("显示"动作).

@RequestMapping("/show/{pressReleaseId}")
@PreAuthorize("permitAll")
public ModelAndView show(@PathVariable long pressReleaseId) {
    ModelAndView modelAndView = new ModelAndView(view("show"));

    modelAndView.addObject("pressRelease",
        sysAdminService.findPressRelease(pressReleaseId));

    return modelAndView;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,Spring Security抛出了这个异常:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:321)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:195)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
Run Code Online (Sandbox Code Playgroud)

如何让Spring Security不抛出此异常?我只是想让任何人进入 - 非经过身份验证的用户和经过身份验证的用户 - 每个人.

我唯一的解决方案就是将这个方法完全放在另一个控制器中,而根本没有@PreAuthorize ......这将起作用,但那是愚蠢的.我想在同一个控制器中保留我的所有新闻稿动作.

谢谢您的帮助!

axt*_*avt 10

我猜你没有启用匿名身份验证过滤器.

如果使用命名空间配置auto-config = "true",则默认情况下应启用它.如果您不使用自动配置,则可以启用匿名过滤器<security:anonymous />.


gut*_*tch 3

允许任何人访问控制器方法的正常方法是不使用任何 Spring Security 注释对其进行注释;即不@PreAuthorize不等@Secured

您应该能够简单地@PreAuthorizeshow()方法中删除,将注释保留在该控制器中的其他方法上。无论您如何使用该show()方法,其他方法都将保持安全。

  • 值得一试;)但是不行,行不通。哦,好吧...我有很多控制器都有不同的安全问题,我认为这对 Spring Security 来说太混乱了,迫使开发人员单独测试每个操作而不使用类级别的默认值。我必须告诉他们解决这个问题,因为这对于大型应用程序来说非常糟糕。 (2认同)