如何使用Spring(java)验证Facebook授权令牌并注册用户

时间:2018-12-20 14:43:49

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

我正在开发一个应用程序,其前端是使用React.js编写的,后端REST API是使用Spring框架编写的。我想将社交登录信息添加到我的网站,因此经过数天的搜索和研究,我了解到OAuth2是解决方案。我知道前端应该处理从资源服务器(此处为Facebook)获取授权令牌的工作,而后端(java)应验证该令牌并与Facebook连接以获得访问令牌。然后,该访问令牌应与用户详细信息(例如电子邮件)一起存储在我的数据库中。

这是我的要求,一旦用户单击“继续使用Facebook” 按钮,我的应用应使用自己的详细信息-电子邮件和姓名(注册功能)在自己的数据库中创建该帐户。之后,每当他们再次单击该按钮时,他们将登录并没有注册。其他网站的处理方式。

到目前为止,我的应用程序中已有该按钮,这使我从Facebook获得了授权令牌。

有人可以指导我在这里走的路吗?

此外,对于某些错误处理,我应该特别注意。

1 个答案:

答案 0 :(得分:7)

这是使用Spring Boot作为REST API的通用方法,该方法由Spring Data JPA和Spring Security支持,可同时适用于iOS和ember.js。可能有库,您不能使用什么,但是我将概述基本流程。

  1. 您的用户对象需要一个与Facebook帐户的一对一映射。最佳做法是在存储在数据库中之前先对authToken进行加密
@Entity
class FacebookAccount {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    Long id

    String facebookUserId
    String authToken

    @OneToOne
    @JoinColumn(name="user_id")
    User user
}
@Entity
class User{

...
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    FacebookAccount facebookAccount
}
  1. 使用facebook Javascript SDK获取用户访问令牌和用户的Facebook用户ID。在成功的情况下,您将在您的react应用中收到来自Facebook的回复:
{
    status: 'connected',
    authResponse: {
        accessToken: '...',
        expiresIn:'...',
        reauthorize_required_in:'...'
        signedRequest:'...',
        userID:'...'
    }
}
  1. 使用第2步中收到的信息(例如/login/facebook)打一些登录端点。我无法预测您的应用的结构。在我的应用中,此代码由实现GenericFilterBean的身份验证过滤器处理。我将标头X-Auth-Facebook传递给令牌。

  2. 验证令牌。我在AuthenticationProvider方法内实现Authentication authenticate(Authentication authentication) throws AuthenticationException的类中进行此操作。此类需要您的应用的访问令牌accessToken和用户的令牌userAccessToken

URIBuilder builder = URIBuilder.fromUri(String.format("%s/debug_token", "https://graph.facebook.com"))
builder.queryParam("access_token", accessToken)
builder.queryParam("input_token", userAccessToken)
URI uri = builder.build()
RestTemplate restTemplate = new RestTemplate()

JsonNode resp = null
try {
    resp = restTemplate.getForObject(uri, JsonNode.class)
} catch (HttpClientErrorException e) {
    throw new AuthenticationServiceException("Error requesting facebook debug_token", e)
}

Boolean isValid = resp.path("data").findValue("is_valid").asBoolean()
if (!isValid)
    throw new BadCredentialsException("Token not valid")

String fbookUserId = resp.path("data").findValue("user_id").textValue()
if (!fbookUserId)
    throw new AuthenticationServiceException("Unable to read user_id from facebook debug_token response")

// spring data repository that finds the FacebookAccount by facebook user id
FacebookAccount fbookAcct = facebookAccountRepository.findByFacebookUserId(fbookUserId)
if(!fbookAcct){
    // create your user here
    // save the facebook account as well
} else{
  // update the existing users token
  fbookAcct.authToken = userAccessToken
  facebookAccountRepository.save(fbookAcct)
}
// finish the necessary steps in creating a valid Authentication

我个人然后创建一个令牌,供我的客户在访问我的API时使用(而不是让他们继续通过所有请求传递facebook令牌)。

我还需要更多用户提供的信息来创建用户(选择的用户名,同意条款和条件等)。因此,我的实际实现方式抛出一个EntityNotFoundException而不是创建用户,我的客户然后使用该用户弹出一个注册表单,该表单仅提供我无法从facebook获得的字段。从客户端提交此消息后,我用Facebook令牌以及创建用户所需的内容命中了/signup/facebook端点。我从facebook获取个人资料并创建用户(在此过程中自动记录他们)。

编辑:如果要使用Spring 0Auth,可以按照example创建Spring 2 Oauth Rest模板

@Bean
public OAuth2ProtectedResourceDetails facebook() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setId("facebook");
    details.setClientId("233668646673605");
    details.setClientSecret("33b17e044ee6a4fa383f46ec6e28ea1d");
    details.setAccessTokenUri("https://graph.facebook.com/oauth/access_token");
    details.setUserAuthorizationUri("https://www.facebook.com/dialog/oauth");
    details.setTokenName("oauth_token");
    details.setAuthenticationScheme(AuthenticationScheme.query);
    details.setClientAuthenticationScheme(AuthenticationScheme.form);
    return details;
}

@Bean
public OAuth2RestTemplate facebookRestTemplate(OAuth2ClientContext clientContext) {
    OAuth2RestTemplate template = new OAuth2RestTemplate(facebook(), clientContext);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,
            MediaType.valueOf("text/javascript")));
    template.setMessageConverters(Arrays.<HttpMessageConverter<?>> asList(converter));
    return template;
}

然后在使用中:

public String photos(Model model) throws Exception {
        ObjectNode result = facebookRestTemplate
                .getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
        ArrayNode data = (ArrayNode) result.get("data");
        ArrayList<String> friends = new ArrayList<String>();
        for (JsonNode dataNode : data) {
            friends.add(dataNode.get("name").asText());
        }
        model.addAttribute("friends", friends);
        return "facebook";
    }

我从项目中接受了以上要求的朋友。使用debug_token显示的上述代码使用Spring OAuth rest模板应该很容易。希望这会有所帮助:)