如何从ui.router

时间:2017-04-29 08:40:48

标签: angular angular-ui-router auth0

我有一个使用auth0.js进行身份验证的angular1应用程序。 当我的应用程序从auth0接收回调时,我想将令牌存储在我的tokenService中。

https://localhost:44316/Run#access_token=ufgdfgfdNCRfYBP&expires_in=86400&id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2Ryb2JsZXIuZXUuYXV0gDfgAuY29tLyIsInN1fgf6Imdvb2dsZS1vYXV0aDJ8MTAzOTAwNjAwNjI0MTg2MTIyMDAwIiwiYXVkIjoieU1XYUt3VmF1ckhsaU5hemZVM3c0QUtzV2hXVEFJSHIiLCJleHAiOjE0OTM0ODk0MDgsImlhdCI6MTQ5MzQ1MzQwOH0.NuRxvsOIoB5_zZLl5aZd7zYgAhXxpvEhXXDJ1dkurRo&token_type=Bearer

如何创建与url匹配的ui.router状态,以便我的决心可以 处理请求并获取其他数据?

$stateProvider
        .state('RecieveAuth', {
            url: "",
            resolve: tokenresolve,
            controller: function($tate){
                $state.go("MainSite");
            },
            data: { requirelanguage: true, requireLogin: true },

        })

不起作用,如果我使用“/”作为网址则不匹配“#accesstoken =”

我已经尝试在运行中进行处理,但是在这个版本中我不知道如何让控制器等待我的http调用完成。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我找到了使用注射器的解决方法:

 $urlRouterProvider.otherwise(function ($injector, $location) {
        var state = $injector.get('$state');
        var $rootScope = $injector.get("$rootScope");
        var accountSvc = $injector.get("accountSvc");
        var tokenService = $injector.get("tokenService");

        console.log('location', $location, 'location.search()', $location.search());

        if ($location.$$url.indexOf('/access_token=') >= 0) {
            accountSvc.authenticateAndGetProfile(function () {
                tokenService.Reload();
                $rootScope.Authenticate();
                state.go('Folders');
            }, function () {
                state.go('Folders');

            });
        }
        return $location.path();
    });

答案 1 :(得分:0)

在您的解析函数中,例如从任何工厂调用服务(数据是工厂的地方):

$stateProvider
    .state('RecieveAuth', {
        url: "",
        resolve: {
            content: function(Data) {
                return Data.isAuth()
            }
        },
        controller: function($tate){
            $state.go("MainSite");
        },
        data: { requirelanguage: true, requireLogin: true },

    })

在您的数据工厂中,isAuth()函数可能如下所示:

let isAuth = function() {
    // Get Token from URL or local storage
    let urlParameters = $location.search();
    let token = '';

    if ( urlParameters.hasOwnProperty('accesstoken') ) {
      tokenSurvey = urlParameters['accesstoken'];
    }

    let deferred = $q.defer();
    $resource('Call your server with the token retrieved above').query().$promise.then( (data) => {
        //User successfully, auth, rreturn resolve promise
        deferred.resolve(data);
      },
      (error) => {
        // Eror during Auth, reject promise, state will not be loaded (you have to handle errors in this case)
        deferred.reject(error);
      });
    return deferred.promise;
  };