java Spring security 4 @PreAuthorize(hasAuthority()) 访问被拒绝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39313954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring security 4 @PreAuthorize(hasAuthority()) access denied
提问by ericcire
I am trying to convert a Spring Security 3 @Secured("admin") annotation into Spring Security 4 compatible fashion.
我正在尝试将 Spring Security 3 @Secured("admin") 注释转换为 Spring Security 4 兼容的方式。
This is my usersService.java
这是我的 usersService.java
@PreAuthorize("hasAuthority('admin')")
public List<User> getAllUsers() {
return usersDao.getAllUsers();
}
Then in security-context.xml
I have:
然后在security-context.xml
我有:
<security:intercept-url pattern="/admin" access="permitAll" />
...
<security:global-method-security pre-post-annotations="enabled" />
getAllUsers()
is called by a LoginController.java
getAllUsers()
被一个调用 LoginController.java
@RequestMapping("/admin")
public String showAdmin(Model model) {
List<User> users = usersService.getAllUsers();
model.addAttribute("users", users);
return "admin";
}
In mySql database, there are two tables, users and authorities. authorities
has 2 columns, username and authority. administrator
has authority admin
.
在mySql数据库中,有两个表,用户和权限。authorities
有 2 列,用户名和权限。administrator
有权限admin
。
Now if I trie to access /admin
, I will be redirected to /login
, but after I log in with administrator
, I still get "access denied".
现在,如果我尝试访问/admin
,我将被重定向到/login
,但在使用 登录后administrator
,我仍然收到“拒绝访问”。
I think I must have missed something very basic but as I am new to Spring, I could not figure it out. Any help would be appreciated. Thanks.
我想我一定错过了一些非常基本的东西,但由于我是 Spring 的新手,我无法弄清楚。任何帮助,将不胜感激。谢谢。
Update: I tried changing the annotation to @PreAuthorize("hasRole('ROLE_ADMIN')") and I also changed the "authority" column in mySql for admin from "admin" to "ROLE_ADMIN" but it still gives me 403. I did not have much faith on this because before this error, I had to change hasRole('admin')
in securityContext.xml
to hasAuthority('admin')
.
更新:我尝试将注释更改为 @PreAuthorize("hasRole('ROLE_ADMIN')") 并且我还将 mySql 中用于 admin 的“authority”列从“admin”更改为“ROLE_ADMIN”,但它仍然给了我 403。我做到了没有这多少信心,因为这个错误之前,我不得不改变hasRole('admin')
在securityContext.xml
给hasAuthority('admin')
。
回答by LeO
Although it's late, nevertheless
虽然晚了,但是
hasRole(...)
set a prefix for the the content - the default one is ROLE_
hasRole(...)
为内容设置前缀 - 默认是 ROLE_
hasAuthority(...)
checks the content WITHOUTa prefix, i.e. just the pure content
hasAuthority(...)
检查没有前缀的内容,即只是纯内容
回答by Sohil
Try this @PreAuthorize("hasRole('ROLE_ADMIN')")
试试这个 @PreAuthorize("hasRole('ROLE_ADMIN')")
回答by Самир Шахмурадлы
You should add in Spring security
您应该添加 Spring 安全性
@EnableGlobalMethodSecurity(prePostEnabled = true)