2017-05-21 175 views
0

我使用Spring Security来保护我的REST Apis。依赖注入检索SecurityContext对象

我能够找回注入的主要对象在我RestController:

@GetMapping("/user") 
public ResponseEntity<User> getUser(Principal user) { 
user.getName(); 

但不幸的是,校长对象没有getAuthorities()方法,我需要读出用户的角色。

这就是为什么我用静态方法来获得所需的信息,我需要什么:

@GetMapping("/user") 
public ResponseEntity<User> getUser() { 
//how to get the SecurityContext by DI ? 
Authentication user = SecurityContextHolder.getContext().getAuthentication(); 

有没有简单的解决方案,使由依赖注入当前的SecurityContext对象?

+0

见http://docs.spring.io/spring-security/site/文档/ 4.2.2.RELEASE /参考/ htmlsingle /#MVC-认证主要 –

回答

0

请尝试以下方法:

@RequestMapping("/authentication") 
Authentication getAuthentication(Authentication authentication) { 
    return authentication; 
} 

它由ServletRequestMethodArgumentResolver支持,Authentication是子类的Principal

if (Principal.class.isAssignableFrom(paramType)) { 
     return request.getUserPrincipal(); 
    }