programing

AngularJS + OAuth

cafebook 2023. 4. 3. 21:45
반응형

AngularJS + OAuth

Angular App 로그인 솔루션을 작성하려고 합니다.
이는 사용자가 Facebook/Google/Twitter 또는 Register를 통해 정상적으로 연결할 수 있음을 의미합니다.
Angular-OAuth는 유용하지만 Facebook(또는 Twitter)에서는 작동하지 않는 것 같습니다.

이 모든 것을 망라하는 솔루션을 아는 사람?

다음은 angular js와 함께 리다이렉트만 사용하는 간단한 예입니다.

다음으로 인증으로 리다이렉트 하는 방법을 나타냅니다.

angular.module('angularoauthexampleApp')
  .controller('MainCtrl', function ($scope) {
    $scope.login=function() {
        var client_id="your client id";
        var scope="email";
        var redirect_uri="http://localhost:9000";
        var response_type="token";
        var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
        "&response_type="+response_type;
        window.location.replace(url);
    };
  });

인증 후 리다이렉트를 처리하는 방법은 다음과 같습니다.

angular
  .module('angularoauthexampleApp', [
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/access_token=:accessToken', {
        template: '',
        controller: function ($location,$rootScope) {
          var hash = $location.path().substr(1);

          var splitted = hash.split('&');
          var params = {};

          for (var i = 0; i < splitted.length; i++) {
            var param  = splitted[i].split('=');
            var key    = param[0];
            var value  = param[1];
            params[key] = value;
            $rootScope.accesstoken=params;
          }
          $location.path("/about");
        }
      })
  });

상세한 것에 대하여는, http://anandsekar.github.io/oauth2-with-angularjs/ 를 참조해 주세요.

oauth를 보세요.이오

  • Javascript에서의 간단한 구현
  • 80개 이상의 OAuth 프로바이더
  • 빠르고 안전한

freemium oauth.io 대신 free-Open-Source가 있습니다.hello .

Github의 Satelliteizer 프로젝트를 보세요.이제 막 시작했는데 유망해 보이네요.

JSON Web 토큰을 사용하여 이메일+패스워드, Facebook, Twitter, Google 및 기타 OAuth 1.0/2.0 공급자를 통한 로그인을 허용합니다.

클라이언트측 코드에 의해서, 서버측을 직접 실장할 필요가 있습니다.많은 서버 측 언어의 워크플로우와 코드 예에 대한 적절한 설명이 있습니다.

위에서 설명한 OAuth.io 솔루션의 Angular 코드 샘플과 코멘트를 추가하고 싶습니다.설립자가 말한 바와 같이 유료 서비스이지만, 저는 다음과 같은 두 가지 주요 이점이 있다고 생각합니다.

  • Facebook, Twitter 등 OAuth 프로바이더에 접속하는 일관된 방법을 제공합니다.즉, 각 OAuth 프로바이더 구현의 모든 특성을 숨깁니다.
  • 프론트 엔드 코드만을 사용하여 OAuth 소셜 버튼을 구현할 수 있습니다.

프런트 엔드 코드도 비교적 심플합니다.코더월에서 가져왔어요

import {Component, OnInit} from '@angular/core';

function _window(): any {
  // return the global native browser window object
  return window;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  ngOnInit(): void {
    const oauthScript = document.createElement('script');
    oauthScript.src = 'https://cdn.rawgit.com/oauth-io/oauth-js/c5af4519/dist/oauth.js';

    document.body.appendChild(oauthScript);
  }

  handleClick(e) {
    // Prevents page reload
    e.preventDefault();

    // Initializes OAuth.io with API key
    // Sign-up an account to get one
    _window().OAuth.initialize('YOUR OAUTH.IO PUBLIC KEY');

    // Popup Github and ask for authorization
    _window().OAuth.popup('github').then((provider) => {

      // Prompts 'welcome' message with User's name on successful login
      // Check console logs for additional User info
      provider.me().then((data) => {
        console.log('data: ', data);
        alert('Welcome ' + data.name + '!');
      });

      // You can also call Github's API using .get()
      provider.get('/user').then((data) => {
        console.log('self data:', data);
      });
    });
  }
}

언급URL : https://stackoverflow.com/questions/18218293/angularjs-oauth

반응형