如何将我的业务逻辑添加到spring cloud oauth的身份验证中?

时间:2018-01-19 01:46:41

标签: spring-boot spring-security jwt spring-security-oauth2

在oauth服务器端(auth microservice),我尝试通过spring security和jwt实现oauth中心,这是我的UserDetailService的代码:

@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws 
UsernameNotFoundException {
    ManagerInfo managerInfo = userMapper.getUserByLoginName(username);
    if(managerInfo ==null)
        throw new UsernameNotFoundException("sorry,can not find user of "+username+"!");
    Collection<Role> roleList =roleMapper.getRoleByUserId(managerInfo.getId());
    String roleIds = roleList.stream().map(role ->role.getId().toString()).collect(Collectors.joining(","));
    Collection<Authority> authorities =authorityMapper.getAuthoritiesByRoleIds(roleIds);
    CustomUserPrincipal userDetail = new CustomUserPrincipal(managerInfo.getUsername(),managerInfo.getPassword(),
authorities);
    userDetail.setUser(managerInfo);
    return userDetail;
}

CustomUserprincipal只是扩展了org.springframework.security.core.userdetails.User,而且Authority实现了org.springframework.security.core.GrantedAuthority。

在我的网关项目中,我尝试使用spring boot(版本:1.5.9.RELEASE),这里有一些依赖:

<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
</dependency> 

现在,我已经通过“prePostEnabled”方式成功验证了用户,这里是控制器代码:

@RequestMapping(value = "/getUserById/{id}",method = RequestMethod.GET)
@PreAuthorize("hasAnyAuthority('LIST_USER')")
CollectionAccount getUserById(@PathVariable String id){
   return managerService.getCollectionAccount(Long.parseLong(id));
}

我编写的所有代码都很好用,并且用户具有'LIST USER'权限,userdetailservice返回的权限可以访问此方法。

但是,如果我想按资源类型验证用户,而不仅仅是权限字符串,该怎么办?

或者在身份验证中添加一些业务逻辑,例如'A_PARK_LIST_USER','B_PARK_LIST_USER'等,也许用户登录时只有'A_PARK_LIST_USER'并且无法列出“B_PARK”的用户,所以我无法控制只有'LIST USER'访问权限,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您只需将AuthenticationPrincipal注入控制器方法即可。

试试这个:

    @RequestMapping(value = "/getUserById/{id}",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('LIST_USER')")
    CollectionAccount getUserById(@PathVariable String id, @AuthenticationPrincipal Principal principal){
        //Here you have the users information, the principal.getName() will be the username that has been authenticated
        log.debug(principal.getName());
        return managerService.getCollectionAccount(Long.parseLong(id));
    }