Grails Rest API与OAuth for Mobile App

时间:2014-12-11 04:46:53

标签: api rest grails mobile oauth

TL; DR:从编辑1中读取

我正在尝试找到如何实施身份验证的解决方案,尤其是针对移动应用将使用的其余API的OAuth。

我找到了这个流行的插件 Spring Security Rest ):

http://alvarosanchez.github.io/grails-spring-security-rest/docs/guide/single.html#oauth 1

但问题是它是专为javascript前端应用设计的,所以它需要一个回调网址到我的前端传递生成的令牌(如图所示)。

对于移动应用程序,我该怎么做?我可以为此实现另一个插件或设计吗? 我觉得奇怪的是,在Grails或Spring中没有很多关于无状态OAuth的插件或教程,但有大量的移动应用程序使用它。

以下是用例示例:

  • 用户打开移动应用。
  • 用户在移动应用上使用Facebook登录。
  • 用户向api /订单发出请求,只会返回他的订单。

谁应该处理这个OAuth部分?插件中显示的图表中的流程无法与移动应用程序一起使用,因此,如果移动应用程序授权到Facebook,获取令牌存储它然后将其传递给Web应用程序?

我想了解在这种情况下什么是正确的设计/流程,以及是否有插件或使用grails实现它的方法。

编辑:这是正确的流程吗?

Mobile App OAuth + Auth to backend with external provider UML Sequence Diagram

如果是,有没有一种标准方法可以用Grails实现这个?

编辑2:现在我了解了流程,我需要将登录部分与Spring安全休息插件集成(已经处理了其他所有内容)。 这是我想要与插件集成的代码,但我不知道在插件中修改的位置或内容:

    // api/auth/fb
def auth(){

    //Extract fb_access_token
    String fbAccessToken = request.JSON.?fb_access_token

    //Call https://graph.facebook.com/me?access_token=fbAccessToken
    def userInfo = facebookService. ... (fbAcessToken) //Method to use in the plugin

    //Verify if the userInfo contains an error/doesn't contain a fbId
    if(userInfo.getFbId() == null ){
        respond unauthorized() // 401, Invalid access token
    }
    //Verify if this token is for our app
    else if(userInfo.getAppSecret() != System.env.getParameter("appSecret")){
        respond unauthorized() //401, token not for this app
    }
    //Register or login
    else{
        User user = User.findByFbId(userInfo.getFbId())
        if(user == null){
            facebookService.registerUser(userInfo) //Custom method implemented in the service
        }
        else{
            FbToken fbToken = new FbToken(userInfo.getToken(), userInfo.getExpiration())
            user.setFbAccessToken(fbToken)
        }

        //Login the user with spring security and let it handle the rest (token creation => storage => http answer)

    }

}

1 个答案:

答案 0 :(得分:1)

以下是我们如何处理facebook与grails rest插件的连接。

  1. 客户向facebook提出请求并获取fb uid。
  2. 客户端将fb uid与其他详细信息(如电子邮件等)一起发送到服务器(无论是在身份验证后从Facebook获取的内容)
    • 服务器接收fb uid并使用Facebook重新验证fbuid 然后尝试在数据库中找到此fbuid用户。
    • 如果用户发现使用电子邮件登录用户并返回令牌。
    • 如果用户未找到注册并登录用户并发送回令牌。
  3. 客户使用从第2步返回的令牌进行任何后续调用。