PreAuthorize(“ isAuthenticated()”)在RestController上不起作用

HJK*_*HJK 0 java rest json uri spring-security

我发现了许多类似的问题,但是都没有解决我的问题,我的问题是:PreAuthorize(“ isAuthenticated()”)在我的RestController上不起作用。

我的配置安全性是:

<global-method-security pre-post-annotations="enabled"/>
<authentication-manager alias="authenticationManager">
        <authentication-provider>
            <password-encoder ref="passwordEncoder" />
            <jdbc-user-service
                data-source-ref="dataSource"
                users-by-username-query="
         select login,password,1
         from test tst where tst.login=?" 
                authorities-by-username-query="
         select login,'ROLE_SAVE' from test tst where tst.login=?"
            />
        </authentication-provider>
    </authentication-manager> 
Run Code Online (Sandbox Code Playgroud)

在我的RestController上,我添加以下注释:@PreAuthorize(“ isAuthenticated()”)

@RestController
@PreAuthorize("isAuthenticated()")
@RequestMapping("/api/test")
public class PrinterController{

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseStatus test() {
    System.out.println("test");
}
Run Code Online (Sandbox Code Playgroud)

但无法正常工作,任何用户都可以使用此资源。

小智 5

您需要将以下注释添加到您的安全配置类:

@EnableGlobalMethodSecurity(prePostEnabled = true)
Run Code Online (Sandbox Code Playgroud)

由于这篇文章:

https://nixmash.com/post/spring-mvc-method-security-with-preauthorize-and-sp-el