简体   繁体   中英

How to handle the authentication using 3rd party login in Angularjs

By running the code below, the authentication window pops-up and the user confirms the login. This part works. Once the authorize button is clicked, this redirects to the previous tab in the same window (in the pop-up not in the parent window). How I can close this pop-up window after authorization is confirmed by the user and how can I get back the authorization code from the url? For instance in the code below, the first "console.log(event.url);" is not executed.

    var redirectUri = "http://localhost:8100/callback";

    var ref = window.open('https://www.example.com/oauth/authorize?client_id=' + clientID + '&redirect_uri=' + redirectUri + '&scope=write&response_type=code&approval_prompt=force', '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');

    ref.addEventListener('loadstart', function (event) { // THIS IS NOT TRIGGERED FOR SOME REASON

        console.log(event.url); 

        if ((event.url).indexOf(redirectUri) === 0) {
            requestToken = (event.url).split("code=")[1];

            $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            $http({
                    method: "post",
                    url: "https://www.example.com/oauth/token",
                    data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken
                })
                .success(function (data) {
                    $scope.data = data;
                    console.log(event.url);

                })
                .error(function (data, status) {
                    deferred.reject("Problem authenticating");
                });
        }
    });

Below are the tabs used in the application. How can I return to my tab.example after callback?

// setup an abstract state for the tabs directive
    .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
})

.state('tab.example', {
        url: '/example',
        views: {
            'tab-example': {
                templateUrl: 'templates/tab-example.html',
                controller: 'ExampleAPICtrl'
            }
        }
    })
    .state('callback', {


    });

// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/');

You need a service to wrap the 3rd party Provider so it can listen for the event Call back.

a great library implementation I've used:

mrzmyr Angular-Google-Plus

The heart of the librarie's approach is in the following code snippet:

      NgGooglePlus.prototype.login = function () {
          deferred = $q.defer();
          gapi.auth.authorize({
              client_id: options.clientId,
              scope: options.scopes,
              immediate: false,
              approval_prompt: "force",
              max_auth_age: 0
          }, this.handleAuthResult);
          return deferred.promise;
      };

When you want to do login with 3rd party, i advice you to create a login service which will perform the login by sending the good information to the login system (other API, web application with url...). Like that, your service can emit event that can be used in your application to perform more action

$scope.$broadcast('loadstart', {
  someProp: 'send parameter to your event in the data object' 
});

$scope.$on('loadstart', function (event, data) {
  //your function the tretment of the reply
});

If you want to go forward with the event you can follow this link : https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

to return in your tab.example you can try the $state in the .success part of your http request. This service allow you to choose on which state you want to be :

$state.go('tab.example');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM