Jos*_*son 6 spring spring-security
@RequestBody使用Spring Security 获得安全保障的正确方法是什么?
例如:A User可以有多个Blogs,每个Blog可以有多个Entrys.用户去保存某个博客的条目,请求会像这样:
@RequestMapping(value="/api/entry", method=RequestMethod.POST)
@ResponseBody
public Entry save(@Valid @RequestBody Entry entry) {
this.entryService.save(entry);
return entry;
}
Run Code Online (Sandbox Code Playgroud)
现在,传入entry有一个Blog,用户可以篡改请求并选择其他人的博客,有效地将条目发布到他们的博客.虽然我可以在验证中捕获这个(查询持久层以验证Blog属于登录的User)我觉得这应该由Spring Security处理.如果是这样,我该怎么做呢?
我们遇到过这种情况.
这是两个解决方案.我不太喜欢
@RequestMapping(value="/api/entry", method=RequestMethod.POST)
@ResponseBody
@PreAuthorize("#entry.author.name == principal.name)"
public Entry save(@Valid @RequestBody Entry entry, Principal principal) {
this.entryService.save(entry);
return entry;
}
Run Code Online (Sandbox Code Playgroud)
要么
@RequestMapping(value="/api/entry", method=RequestMethod.POST)
@ResponseBody
@PreAuthorize("Decision.isOK(entry, principal)")
public Entry save(@Valid @RequestBody Entry entry, Principal principal) {
this.entryService.save(entry);
return entry;
}
Run Code Online (Sandbox Code Playgroud)
//在这种情况下,Spring将从Decision类中调用静态isOk()方法.它应该返回布尔值.
Spring为方法注入Principal主要授权对象,您不必担心它.启用@PreAuthorize注释
<security:global-method-security pre-post-annotations="enabled" />
第二个使用Aspect.创建方面.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Protector {
}
@Aspect
@Component
public class MyAspect {
@Before("@annotation(com.xyz.Protector)")
public void before(JoinPoint joinPoint) throws Throwable {
//u can get method object from joinPoint object,
Method method = ((MethodSignature)joinPoint.getMethodSignature()).getMethod();
//As long as you have Method object you can read the parameter objects (Entry and Principal) with reflection.
//So Compare here: If entry.getOwner().getId().equal(principal.getName()) blah blah blah
}
}
@RequestMapping(value="/api/entry", method=RequestMethod.POST)
@ResponseBody
@Protector
public Entry save(@Valid @RequestBody Entry entry, Principal principal) {
this.entryService.save(entry);
return entry;
}
Run Code Online (Sandbox Code Playgroud)
如果你有方面,你可以拥有更多的运行时拥有权
另请参阅此ulr
| 归档时间: |
|
| 查看次数: |
2240 次 |
| 最近记录: |