Spring security oauth2:如果不存在则创建用户,提供用户

Vad*_*huk 6 spring spring-mvc spring-security oauth-2.0 spring-security-oauth2

这是spring oauth2 教程的摘录:

如何添加本地用户数据库

许多应用程序需要在本地保存有关其用户的数据,即使将身份验证委托给外部提供者也是如此。我们这里不展示代码,但很容易分两步完成。

为您的数据库选择一个后端,并为适合您需要的自定义 User 对象设置一些存储库(例如使用 Spring Data),并且可以从外部身份验证完全或部分填充。

通过检查 /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;
}
Run Code Online (Sandbox Code Playgroud)

Dave Syer(春季维护者)建议

将 Principal 向下转换为 Authentication(或者可能是 OAuth2Authentication 并从中获取 userAuthentication),然后查看 details 属性。如果您的用户已使用 UserInfoTokenServices 进行身份验证,您将看到从外部提供程序的用户信息端点返回的 Map。

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

  1. 我们为什么要在控制器调用中这样做……它闻起来很香。
  2. 为什么我们还要做所有那些 instanceof 和 casts..smells。

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;
}
Run Code Online (Sandbox Code Playgroud)

oauth2 舞蹈完成后创建用户的最佳方式是什么?