【发布时间】:2018-10-11 10:03:50
【问题描述】:
在带有 Spring Security 的 Spring MVC 中,是否有可能实现这一点?
@Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.mvcMatchers("/users/{authentication.principal.username}").hasAnyRole(ADMIN, MANAGER)
.antMatchers("/users/**").hasRole(ADMIN)
.anyRequest().authorized()
...
}
/users/** 是一个禁区,只能由管理员访问。但是管理员应该仍然能够看到他们自己的个人资料 (/users/user_with_manager_role),而且只能看到他们自己的个人资料,而不是任何其他用户的个人资料(无论他们的角色如何)。
解决方案
我在 Andrew 的回答中找到了解决方案。我的代码现在看起来像这样:
WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // added this annotation
public class SecurityConfig extends WebSecurityConfigurerAdapter
@Override WebSecurityConfigurerAdapter.configure(HttpSecurity)
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
// removed /users handling
.anyRequest().authorized()
...
}
用户控制器
@Controller
@RequestMapping("/users")
public class UsersController
{
@GetMapping("{username}")
@PreAuthorize("authentication.principal.username == #username) || hasRole('ADMIN')")
public String usersGet(@PathVariable("username") String username)
{
// do something with username, for example get a User object from a JPA repository
return "user";
}
}
【问题讨论】:
-
不要将解决方案编辑到您的问题中。只需为您的问题添加一个新答案。因此,我回滚了您的编辑。您可以从历史记录中复制您的答案以添加新答案。
标签: java spring-mvc spring-security authorization