Spring security oauth2:创建用户(如果不存在),配置用户

时间:2016-11-23 04:29:33

标签: spring spring-mvc spring-security oauth-2.0 spring-security-oauth2

以下摘自spring oauth2 tutorial

  

如何添加本地用户数据库

     

许多应用程序需要在本地保存有关其用户的数据,即使这样   身份验证委派给外部提供程序。我们没有显示   代码在这里,但很容易分两步完成。

     

为您的数据库选择后端,并设置一些存储库(例如   使用Spring Data)来获得适合您需求的自定义User对象   可以从外部完全或部分填充   认证

     

为每个登录的唯一用户设置User对象   检查/ user端点中的存储库。如果已经存在了   具有当前Principal身份的用户,可以更新,   否则就创造了。

     

提示:在User对象中添加一个字段以链接到其中的唯一标识符   外部提供者(不是用户的名字,而是一些东西)   对于外部提供商的帐户而言是唯一的。)

因此,在用户控制器中,我们有以下代码:

@RequestMapping("/user")
public Map<String, Object> user(Principal user) {
    Map<String, Object> map = new HashMap<String, Object>();
    // for a facebook the name is facebook id, not an actual name
    map.put("name", user.getName());
    map.put("roles", AuthorityUtils.authorityListToSet(((Authentication) user)
            .getAuthorities()));
    return map;
}

Dave Syer(spring maintainer) suggests to

  

将校长转发为认证(或可能   OAuth2Authentication并从中获取用户身份验证)和   然后查看详细信息属性。如果您的用户已通过身份验证   使用UserInfoTokenServices,您将看到从中返回的Map   外部提供商的用户信息端点。

但对我来说,这似乎不自然有两个原因:

  1. 我们为什么要在控制器呼叫中这样做...它闻起来。
  2. 我们为什么要做所有的instanceof和casts..smells。
  3. 最好是插入OAuth2AuthenticationManager而不是org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
         // ...
        OAuth2Authentication auth = tokenServices.loadAuthentication(token);
        // ...
        auth.setDetails(authentication.getDetails());
        auth.setAuthenticated(true);
        // here we could've create our own Authentication object
        // to set as Principal with application specific info. 
        // Note: no casts are required since we know the actual auth type
        return auth;
    }
    

    在oauth2舞蹈结束后创建用户的最佳方式是什么?

0 个答案:

没有答案