加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:36:52 所属栏目:大数据 来源:网络整理
导读:我的堆栈是: 离子2 Java Spring JWT身份验证 我想在我的应用程序中使用相应的cordova插件实现社交登录按钮(Facebook,Google等),登录用户并在我现有的自定义服务器端API上验证并存储他/她的数据.我无法找到关于如何做到这一点的任何好教程. 我希望我的用户可

我的堆栈是:

>离子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;
    }
}

在后端(Java Spring):

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

    //if user exists return invalid etc.
    Optional

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

最佳答案
以下是有关使用FB和Google Auth的示例演示,但我不是来自Java背景,因此您将只找到客户端解决方案.

服务

让我们实现登录功能的逻辑.在oauth文件夹中创建一个oauth.service.ts文件,并在其中粘贴以下代码:

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

认证提供者和令牌接口
正如我们已经提到的,IOathProvider应该包含一个login()函数.因此,我们应该设置以下接口作为IOathProvider对象的抽象类型/模型.在oauth文件夹中创建一个oauth.provider.interface.ts文件,并在其中包含以下行:

export interface IOathProvider {
    login(): Promise;
}

Facebook和Google身份验证服务

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

安装依赖项

这时ng2-cordova-oauth库就派上用场了.我们可以通过执行命令来安装它:
npm install ng2-cordova-oauth –save

此外,我们的应用程序依赖于Cordova InAppBrowser插件.我们将安装它:

离子插件添加cordova-plugin-inappbrowser

不要忘记在package.json文件中包含cordova-plugin-inappbrowser,因此无论何时从头开始安装项目,它都可以与其余插件一起安装.

实施Facebook和Google身份验证提供程序

让我们在oauth / facebook / path下创建facebook-oauth.provider.ts文件.在此文件中,请在代码段中包含代码:

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

同样,使用ng2-cordova-oauth库提供的CordovaOauth对象,我们将使用自己的login()函数实现Google身份验证提供程序.但是,这里我们从Config传递另一个clientId,它对应于我们使用Google Developer Console配置的应用程序.
因此,请创建一个google-oauth.provider.ts文件并粘贴以下行:

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

完全归功于this文章,你可以在Github找到Working Code.我还没有涵盖整个教程,只包括该教程的部分(谷歌和Facebook).我们需要安装什么插件以及如何使用TypeScript,如果您需要,那么您可以参考该教程

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读