使用现有API的FB/Google客户端登录(Ionic)

Ale*_*dis 6 java spring facebook cordova ionic-framework

我的堆栈是:

  • 离子2
  • Java Spring
  • JWT身份验证

我想在我的应用程序中使用相应的cordova插件实现社交登录按钮(Facebook,Google等),登录用户并在我现有的自定义服务器端API上验证并存储他/她的数据.我无法找到关于如何做到这一点的任何好教程.

我希望我的用户可以使用随机密码保存在数据库中,并且可以从我的应用程序登录.

我想象的是:

(客户端)

FB.login(function(userDetailsAndToken) {
    myBackendAPI.socialLogin(userDetailsAndToken).then(function(user) {
        //Successfully logged in with Facebook!
        this.user = user;
    }
}
Run Code Online (Sandbox Code Playgroud)

在后端(Java Spring):

@PostMapping("/social/account")
public ResponseEntity socialAccount(@Valid @RequestBody FacebookDTO facebookDTO) {
    validateSocialUser(facebookDTO);

    //if user exists return invalid etc.
    Optional<User> existingUser = userRepository.findOneByEmail(facebookDTO.getEmail());
    if (existingUser.isPresent()) {
        return ResponseEntity.badRequest();
    }

    //User doesn't exist. Proceed with login 
    //map from social to my User entity
    User user = socialMapper.toEntity(facebookDTO);

    userService
        .createUser(user.getLogin(), user.getPassword(),
            user.getFirstName(), user.getLastName(),
            user.getEmail().toLowerCase(), user.getImageUrl(),
            user.getLangKey());
    return new ResponseEntity<>(HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)

这可能和安全吗?关于如何实现这一目标的任何好资源/图书馆或指南?

Web*_*ter 4

这是关于使用 FB 和 Google Auth 的示例演示,但我不是来自 Java 背景,因此您只能找到客户端解决方案。

\n\n

服务

\n\n

让\xe2\x80\x99s 实现登录功能的逻辑。在文件夹中创建一个oauth.service.ts文件oauth并将以下代码粘贴到其中:

\n\n
import { Injectable, Injector } from \'@angular/core\';\nimport { FacebookOauthProvider } from \'./facebook/facebook-oauth.provider\';\nimport { IOathProvider } from \'./oauth.provider.interface\';\nimport { GoogleOauthProvider } from \'./google/google-oauth.provider\';\nimport { OAuthToken } from \'./models/oauth-token.model\';\n@Injectable()\nexport class OAuthService {\n    private oauthTokenKey = \'oauthToken\';\n    private injector: Injector;\nconstructor(injector: Injector) {\n        this.injector = injector;\n    }\nlogin(source: string): Promise {\n        return this.getOAuthService(source).login().then(accessToken => {\n            if (!accessToken) {\n                return Promise.reject(\'No access token found\');\n            }\nlet oauthToken = {\n                accessToken: accessToken,\n                source: source\n            };\n            this.setOAuthToken(oauthToken);\n            return oauthToken;\n        });\n    }\ngetOAuthService(source?: string): IOathProvider {\n        source = source || this.getOAuthToken().source;\n        switch (source) {\n            case \'facebook\':\n                return this.injector.get(FacebookOauthProvider);\n            case \'google\':\n                return this.injector.get(GoogleOauthProvider);\n            default:\n                throw new Error(`Source \'${source}\' is not valid`);\n        }\n    }\nsetOAuthToken(token: OAuthToken) {\n        localStorage.setItem(this.oauthTokenKey, JSON.stringify(token));\n    }\ngetOAuthToken(): OAuthToken {\n        let token = localStorage.getItem(this.oauthTokenKey);\n        return token ? JSON.parse(token) : null;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

身份验证提供程序和令牌接口\n正如我们已经提到的,IOathProvider应该包含一个 login() 函数。因此,我们应该设置以下接口来充当对象的抽象类型/模型IOathProvider。在该文件夹中创建一个oauth.provider.interface.ts文件oauth并在其中包含以下行:

\n\n
export interface IOathProvider {\n    login(): Promise;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Facebook 和 Google 身份验证服务

\n\n

下一步,我们应该为我们的应用程序拥有的每个身份验证提供程序实现服务,即FacebookOauthProviderGoogleOauthProvider

\n\n

安装依赖项

\n\n

这时ng2-cordova-oauth图书馆就派上用场了。我们可以通过执行命令来安装它:\nnpm install ng2-cordova-oauth --save

\n\n

此外,我们的应用程序依赖于Cordova InAppBrowser plugin. 我们将使用以下命令安装它:

\n\n

ionic plugin add cordova-plugin-inappbrowser

\n\n

不要忘记cordova-plugin-inappbrowser也将其包含在您的 package.json 文件中,以便您可以在从头开始安装项目时随时将其与其余插件一起安装。

\n\n

实施 Facebook 和 Google 身份验证提供商

\n\n

让\xe2\x80\x99sfacebook-oauth.provider.tsoauth/facebook/ path. 在此文件中,将代码包含在代码片段中:

\n\n
 import { Injectable } from \'@angular/core\';\n    import { Http } from \'@angular/http\';\n    import { IOathProvider } from \'../oauth.provider.interface\';\n    import { CordovaOauth } from \'ng2-cordova-oauth/oauth\';\n    import { Facebook } from \'ng2-cordova-oauth/provider/facebook\';\n    import { Config } from \'../../../config\';\n    interface ILoginResponse {\n        access_token: string;\n    }\n    @Injectable()\n    export class FacebookOauthProvider implements IOathProvider {\n        private cordovaOauth: CordovaOauth;\n        private http: Http;\n        private config: Config;\n        private facebook: Facebook;\n    constructor(http: Http, config: Config) {\n            this.http = http;\n            this.config = config;\n            this.facebook = new Facebook({ clientId: config.facebook.appId, appScope: config.facebook.scope });\n            this.cordovaOauth = new CordovaOauth();\n        }\n    login(): Promise {\n            return this.cordovaOauth.login(this.facebook)\n                .then((x: ILoginResponse) => x.access_token);\n        }\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

类似地,使用CordovaOauth可用的对象ng2-cordova-oauth library,我们将Google authentication provider使用它自己的login()函数来实现 。但是,这里我们clientId从 Config 传递另一个与我们Google使用Google Developer Console. \n因此,创建一个google-oauth.provider.ts文件并粘贴以下行:

\n\n
import { Injectable } from \'@angular/core\';\nimport { IOathProvider } from \'../oauth.provider.interface\';\nimport { OAuthProfile } from \'../models/oauth-profile.model\';\nimport { CordovaOauth } from \'ng2-cordova-oauth/oauth\';\nimport { Google } from \'ng2-cordova-oauth/provider/google\';\nimport { Config } from \'../../../config\';\nimport { Http } from \'@angular/http\';\ninterface ILoginResponse {\n    access_token: string;\n}\n@Injectable()\nexport class GoogleOauthProvider implements IOathProvider {\n    private http: Http;\n    private config: Config;\n    private cordovaOauth: CordovaOauth;\n    private google: Google;\nconstructor(http: Http, config: Config) {\n        this.http = http;\n        this.config = config;\n        this.google = new Google({ clientId: config.google.appId, appScope: config.google.scope });\n        this.cordovaOauth = new CordovaOauth();\n    }\nlogin(): Promise {\n        return this.cordovaOauth.login(this.google).then((x: ILoginResponse) => x.access_token);\n    }\ngetProfile(accessToken: string): Promise {\n        let query = `access_token=${accessToken}`;\n        let url = `${this.config.google.apiUrl}userinfo?${query}`;\nreturn this.http.get(url)\n            .map(x => x.json())\n            .map(x => {\n                let name = x.name.split(\' \');\n                return {\n                    firstName: name[0],\n                    lastName: name[1],\n                    email: x.email,\n                    provider: \'google\'\n                };\n            })\n            .toPromise();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

本文的完整学分,您可以在 Github 中找到工作代码。我没有涵盖整个教程,只涵盖该教程的部分(Google 和 Facebook)。即我们需要安装什么插件以及如何使用 TypeScript 来使用,如果您需要除此之外的内容,那么您可以参考该教程

\n