Acquire Customers Through Facebook and Google by Utilizing API as API Integration for Obtaining Clients from Facebook and Google

To begin, create a new document within the designated folder. Within this document, include the lines pertaining to Facebook and Google authentication services. Moving forward, we must implement the respective services for each authentication provider our application employs, namely Facebook and Google. For encryption and decryption, refer to the RSA Encryption and Decryption tutorial provided below.
Additionally, at the bottom of this page, there are error codes specific to the Facebook Graph API, including the “OAuthException” which relates to the Login Status.


Solution 1:

This demo presents how to work with FB and Google Auth, but please note that I am not proficient in Java, therefore only client-side solutions will be provided.


service

To enable users to log in, we need to implement the appropriate logic. Therefore, we should create a new file named

oauth.service.ts

in the

oauth

directory and insert the code provided below.

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

To establish an abstract model for the MSDTHOT object, an interface for authentication provider and token should be created. The interface should incorporate a login() function as previously stated. To achieve this, the following lines should be included in a file named

oauth.provider.interface.ts

located in the

oauth

folder.

export interface IOathProvider {
    login(): Promise;
}

The authentication services provided by Facebook and Google.

To proceed, we need to establish separate services for every authentication provider our application incorporates, such as

FacebookOauthProvider

and

GoogleOauthProvider

.

Set up the required software components.

When we need to utilize the

ng2-cordova-oauth

library, the

npm install ng2-cordova-oauth --save

command can be executed to install it and make it useful.

Our application depends on the

Cordova InAppBrowser plugin

for its functioning. We will proceed with its installation using the following steps:


ionic plugin add cordova-plugin-inappbrowser

Make sure to add

cordova-plugin-inappbrowser

to your package.json file, enabling it to be installed alongside your other plugins whenever you reinstall your project.

Integrate the authentication providers of Facebook and Google.

Under the

oauth/facebook/ path

directory, make a new file named

facebook-oauth.provider.ts

and insert the code snippet into it.

 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);
        }
    }

By utilizing the object named

CordovaOauth

from

ng2-cordova-oauth library

, we can execute the

Google authentication provider

function along with its corresponding

login()

function. In this scenario, a different

clientId

from Config is passed, which is related to the configured application using

Google

with the assistance of

Google Developer Console

. To proceed, generate a new

google-oauth.provider.ts

file and insert the subsequent lines:

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();
    }
}

The Article deserves all the credit, and the Working Code is available on Github. While I haven’t covered the entire Tutorial, I’ve only discussed the Google and Facebook sections, including the necessary plugins and how to use them in TypeScript. If you require additional information, please refer to the complete tutorial.


Solution 2:


Illustrations extracted from a project of mine involving Java Client designed for JWT Authentication.

import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
    public MicroserviceSecurityConfiguration() {
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .headers()
            .frameOptions()
            .disable()
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/api/profile-info").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/swagger-resources/configuration/ui").permitAll();
    }
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(
            @Qualifier("loadBalancedRestTemplate") RestTemplate keyUriRestTemplate) {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setVerifierKey(getKeyFromAuthorizationServer(keyUriRestTemplate));
        return converter;
    }
    @Bean
    public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
        RestTemplate restTemplate = new RestTemplate();
        customizer.customize(restTemplate);
        return restTemplate;
    }
    private String getKeyFromAuthorizationServer(RestTemplate keyUriRestTemplate) {
        HttpEntity request = new HttpEntity(new HttpHeaders());
        return (String) keyUriRestTemplate
            .exchange("http://someserver/oauth/token_key", HttpMethod.GET, request, Map.class).getBody()
            .get("value");
    }
}

A Java-based back-end is available for social buttons such as Google and Facebook.

import package.repository.SocialUserConnectionRepository;
import package.repository.CustomSocialUsersConnectionRepository;
import package.security.social.CustomSignInAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurer;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.connect.web.ProviderSignInController;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.google.connect.GoogleConnectionFactory;
import org.springframework.social.security.AuthenticationNameUserIdSource;
import org.springframework.social.twitter.connect.TwitterConnectionFactory;
// jhipster-needle-add-social-connection-factory-import-package
import javax.inject.Inject;
/**
 * Basic Spring Social configuration.
 *
 * 

Creates the beans necessary to manage Connections to social services and * link accounts from those services to internal Users.

*/ @Configuration @EnableSocial public class SocialConfiguration implements SocialConfigurer { private final Logger log = LoggerFactory.getLogger(SocialConfiguration.class); @Inject private SocialUserConnectionRepository socialUserConnectionRepository; @Inject Environment environment; @Bean public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) { ConnectController controller = new ConnectController(connectionFactoryLocator, connectionRepository); controller.setApplicationUrl(environment.getProperty("spring.application.url")); return controller; } @Override public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment) { // Google configuration String googleClientId = environment.getProperty("spring.social.google.clientId"); String googleClientSecret = environment.getProperty("spring.social.google.clientSecret"); if (googleClientId != null && googleClientSecret != null) { log.debug("Configuring GoogleConnectionFactory"); connectionFactoryConfigurer.addConnectionFactory( new GoogleConnectionFactory( googleClientId, googleClientSecret ) ); } else { log.error("Cannot configure GoogleConnectionFactory id or secret null"); } // Facebook configuration String facebookClientId = environment.getProperty("spring.social.facebook.clientId"); String facebookClientSecret = environment.getProperty("spring.social.facebook.clientSecret"); if (facebookClientId != null && facebookClientSecret != null) { log.debug("Configuring FacebookConnectionFactory"); connectionFactoryConfigurer.addConnectionFactory( new FacebookConnectionFactory( facebookClientId, facebookClientSecret ) ); } else { log.error("Cannot configure FacebookConnectionFactory id or secret null"); } // Twitter configuration String twitterClientId = environment.getProperty("spring.social.twitter.clientId"); String twitterClientSecret = environment.getProperty("spring.social.twitter.clientSecret"); if (twitterClientId != null && twitterClientSecret != null) { log.debug("Configuring TwitterConnectionFactory"); connectionFactoryConfigurer.addConnectionFactory( new TwitterConnectionFactory( twitterClientId, twitterClientSecret ) ); } else { log.error("Cannot configure TwitterConnectionFactory id or secret null"); } // jhipster-needle-add-social-connection-factory } @Override public UserIdSource getUserIdSource() { return new AuthenticationNameUserIdSource(); } @Override public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) { return new CustomSocialUsersConnectionRepository(socialUserConnectionRepository, connectionFactoryLocator); } @Bean public SignInAdapter signInAdapter() { return new CustomSignInAdapter(); } @Bean public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository, SignInAdapter signInAdapter) throws Exception { ProviderSignInController providerSignInController = new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, signInAdapter); providerSignInController.setSignUpUrl("/social/signup"); providerSignInController.setApplicationUrl(environment.getProperty("spring.application.url")); return providerSignInController; } @Bean public ProviderSignInUtils getProviderSignInUtils(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) { return new ProviderSignInUtils(connectionFactoryLocator, usersConnectionRepository); } } package package.repository; import package.domain.SocialUserConnection; import org.springframework.social.connect.*; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class CustomSocialUsersConnectionRepository implements UsersConnectionRepository { private SocialUserConnectionRepository socialUserConnectionRepository; private ConnectionFactoryLocator connectionFactoryLocator; public CustomSocialUsersConnectionRepository(SocialUserConnectionRepository socialUserConnectionRepository, ConnectionFactoryLocator connectionFactoryLocator) { this.socialUserConnectionRepository = socialUserConnectionRepository; this.connectionFactoryLocator = connectionFactoryLocator; } @Override public List findUserIdsWithConnection(Connection> connection) { ConnectionKey key = connection.getKey(); List socialUserConnections = socialUserConnectionRepository.findAllByProviderIdAndProviderUserId(key.getProviderId(), key.getProviderUserId()); return socialUserConnections.stream() .map(SocialUserConnection::getUserId) .collect(Collectors.toList()); }; @Override public Set findUserIdsConnectedTo(String providerId, Set providerUserIds) { List socialUserConnections = socialUserConnectionRepository.findAllByProviderIdAndProviderUserIdIn(providerId, providerUserIds); return socialUserConnections.stream() .map(SocialUserConnection::getUserId) .collect(Collectors.toSet()); }; @Override public ConnectionRepository createConnectionRepository(String userId) { if (userId == null) { throw new IllegalArgumentException("userId cannot be null"); } return new CustomSocialConnectionRepository(userId, socialUserConnectionRepository, connectionFactoryLocator); }; } package package.security.social; import package.config.JHipsterProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.social.connect.Connection; import org.springframework.social.connect.web.SignInAdapter; import org.springframework.web.context.request.NativeWebRequest; import javax.inject.Inject; public class CustomSignInAdapter implements SignInAdapter { @SuppressWarnings("unused") private final Logger log = LoggerFactory.getLogger(CustomSignInAdapter.class); @Inject private UserDetailsService userDetailsService; @Inject private JHipsterProperties jHipsterProperties; @Override public String signIn(String userId, Connection> connection, NativeWebRequest request) { UserDetails user = userDetailsService.loadUserByUsername(userId); Authentication newAuth = new UsernamePasswordAuthenticationToken( user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuth); return jHipsterProperties.getSocial().getRedirectAfterSignIn(); } }

Example for JWT only

import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.Cookie;
public class CustomSignInAdapter implements SignInAdapter {
    @SuppressWarnings("unused")
    private final Logger log = LoggerFactory.getLogger(CustomSignInAdapter.class);
    private final UserDetailsService userDetailsService;
    private final JHipsterProperties jHipsterProperties;
    private final TokenProvider tokenProvider;
    public CustomSignInAdapter(UserDetailsService userDetailsService, JHipsterProperties jHipsterProperties,
            TokenProvider tokenProvider) {
        this.userDetailsService = userDetailsService;
        this.jHipsterProperties = jHipsterProperties;
        this.tokenProvider = tokenProvider;
    }
    @Override
    public String signIn(String userId, Connection> connection, NativeWebRequest request){
        try {
            UserDetails user = userDetailsService.loadUserByUsername(userId);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                user,
                null,
                user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            String jwt = tokenProvider.createToken(authenticationToken, false);
            ServletWebRequest servletWebRequest = (ServletWebRequest) request;
            servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
        } catch (AuthenticationException ae) {
            log.error("Social authentication error");
            log.trace("Authentication exception trace: {}", ae);
        }
        return jHipsterProperties.getSocial().getRedirectAfterSignIn();
    }
    private Cookie getSocialAuthenticationCookie(String token) {
        Cookie socialAuthCookie = new Cookie("social-authentication", token);
        socialAuthCookie.setPath("/");
        socialAuthCookie.setMaxAge(10);
        return socialAuthCookie;
    }
}

JHipsterProperties serves as an intermediate layer preceding the basic Properties configuration. It is produced by JHipster. By creating a monolithic application, you can refer to the implemented examples to learn how the backend and frontend can be set up to facilitate social buttons.


Solution 3:


To ensure the security of data stored in a Database, one should utilize a hashing algorithm such as HMAC SHA 256. As hashing is a one-way process, decryption of the data is not possible. To perform hashing, a key is required, which can be either static or dynamic depending on the specific needs. The encrypted key should be stored in the Database using any of the
RSA encryption algorithms
methods, and during hashing, the key can be decrypted and passed into the hashing method.

To do Hashing use apache HmacUtils.

String hashedPassword = HmacUtils.hmacSha1Hex(password,passwordkey);

For performing encryption and decryption, refer to the RSA Encryption and Decryption tutorial provided below.

Frequently Asked Questions