dal*_*lcu 6 spring-mvc spring-security spring-data spring-data-rest
我正在使用Spring-Data/Rest(http://docs.spring.io/spring-data/rest/docs/current/reference/html/)和Spring Boot以及基本的Spring Security.
我有以下实体.
Items
-->ID
User
--> ID
--> List<Items> items
Run Code Online (Sandbox Code Playgroud)
目前有弹簧休息,任何用户都可以看到/ items/1,2,3,4,5
我只想让用户,只看到自己的项目.
这是否可以实现而无需编写自定义控制器?
Ash*_*Rao -1
是的,你可以。
为此,您可以做的是为每个用户分配一个特定的角色。例如,在您的情况下,将拥有项目的用户分配为角色列 ADMIN 和所有其他 ANONYMOUS 或 USER,您选择。之后,使用 spring security 您可以使对于项目 URL 具有 ANONYMOUS 或 USER 角色的用户,请求会失败,并且仅允许具有 ADMIN 角色的用户查看项目。
现在,这可以通过 Spring Security 以多种方式实现:
1.对各个控制器方法使用 @PreAuthorize 标签并测试角色 ADMIN/USER/.. 但是,我猜,您不想大幅修改控制器。
简短的手动方法,即将身份验证对象创建到上下文持有者中并使用 Spring Boot 安全配置,如下所示:
@Order(1)
public class UserFilter extends Filter {
@Autowired
UserService userService;
...
UserObject userObject = userService.getUser(arg..);
List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
grantedAuthorityList.add( new SimpleGrantedAuthority((userObject.getRoleName()));//Either ROLE_ADMIN or ROLE_USER
Authentication authentication = new PreAuthenticatedAuthenticationToken(userObject.getId(), new Object(), grantedAuthorityList);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request,response);
...
}
Run Code Online (Sandbox Code Playgroud)以及安全配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfigREST extends WebSecurityConfigurerAdapter {
SecurityConfigREST(){
super(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PreAuthenticatedAuthenticationProvider pap=new PreAuthenticatedAuthenticationProvider();
pap.setPreAuthenticatedUserDetailsService(new PreAuthenticatedGrantedAuthoritiesUserDetailsService());
auth.authenticationProvider(pap);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("^/items.*$").hasAuthority("ROLE_ADMIN") //The role which should have access to /items/1,2.. URL
.anyRequest().authenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
话虽如此,不通过 URL 传递项目 (1,2,3) 数字也是一个很好的设计,因为以后可能会导致潜在的问题,因此使用 GET 并将 JSON 请求正文传递给它,例如:
/items RequestMethod.GET
{
"itemList" : [1,2,3,4,5]
}
Hope that helps.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1652 次 |
| 最近记录: |