PreAuthorize("isAuthenticated()") 不适用于 RestController

问题描述 投票:0回答:2

我发现了很多类似的问题,但没有一个能解决我的问题我的问题是: 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> 

在我的 RestController 上添加此注释:@PreAuthorize("isAuthenticated()")

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

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

但不起作用任何用户都可以使用此资源。

java json rest spring-security uri
2个回答
14
投票

2024 年春季安全 6

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

@EnableMethodSecurity()

prePostEnabled
默认开启。

参考:https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html

2018年答案

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

@EnableGlobalMethodSecurity(prePostEnabled = true)

感谢这篇文章:

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


-1
投票

@PreAuthorize
替换为
@Secured
并在安全 xml 文件中添加
secured-annotations="enabled"
后,问题已解决。

<global-method-security secured-annotations="enabled"/>

在我的 RestController 上

@Secured
© www.soinside.com 2019 - 2024. All rights reserved.