【问题标题】:Satellizer JWT token add user Info into payloadSatellizer JWT 令牌将用户信息添加到有效负载中
【发布时间】:2016-05-03 18:48:58
【问题描述】:

我希望能够使用 Satellizer 将用户角色添加到 JWT 的 Payload 部分,这样我就可以通过我的页面通过 $rootScope 访问它

这是我的身份验证控制器

function() {

'use strict';

angular
    .module('app')
    .controller('AuthController', AuthController);


function AuthController($auth, $state, $http, $rootScope) {

    var vm = this;
    vm.loginErrorText;

    vm.login = function() {

        var credentials = {
            email: vm.email,
            password: vm.password
        }

        // Use Satellizer's $auth service to login
        $auth.login(credentials).then(function(data) {

            return $http.get('api/authenticate/user');


        }).catch(function(response) {

                vm.loginErrorText = response.statusText

        }).then(function(response){

            // Stringify the returned data to prepare it
            // to go into local storage
            var user = JSON.stringify(response.data.user);

            // Set the stringified user data into local storage
            localStorage.setItem('user', user);

            // The user's authenticated state gets flipped to
            // true so we can now show parts of the UI that rely
            // on the user being logged in
            $rootScope.authenticated = true;

            // Putting the user's data on $rootScope allows
            // us to access it anywhere across the app
            $rootScope.currentUser = response.data.user;

            // Everything worked out so we can now redirect to
            // the users state to view the data
            console.log(response.data.user.role);
            $state.go('dashboard');                
        });
    }

}

})();

这里是检查用户角色的运行方法,我可以通过 sub 访问用户的 id,但是有什么方法可以将用户滚动传递给 jwt 有效负载部分?

 .run(function($rootScope, $state, $auth) {

        $rootScope.$on('$stateChangeStart', function(event, toState) {

            // Grab the user from local storage and parse it to an object
            var user = JSON.parse(localStorage.getItem('user'));  


            if(user) {

                // The user's authenticated state gets flipped to
                // true so we can now show parts of the UI that rely
                // on the user being logged in
                $rootScope.authenticated = true;

                // Putting the user's data on $rootScope allows
                // us to access it anywhere across the app. Here
                // we are grabbing what is in local storage
                $rootScope.currentUser = user;

                //getting user ID from JWT
                console.log('Payload : ' + $auth.getPayload().sub);

                // If the user is logged in and we hit the auth route we don't need
                // to stay there and can send the user to the main state
                if(toState.name === "login") {

                    // Preventing the default behavior allows us to use $state.go
                    // to change states
                    event.preventDefault();

                    // go to the "main" state which in our case is users
                    $state.go('dashboard');
                }       
            }
        });
    });

【问题讨论】:

    标签: angularjs laravel jwt


    【解决方案1】:

    有效负载在后端(Laravel)中定义。我假设您正在关注 this guide 。在 AuthenticateController 中,而不是:

        //AuthenticateController.php
        public function authenticate(Request $request)
        {
            $credentials = $request->only('email', 'password');
    
            try {
                if (! $token = JWTAuth::attempt($credentials)) {
                    return response()->json(['error' => 'invalid_credentials'], 401);
                }
         ...
    

    我正在使用:

        //AuthenticateController.php
        public function authenticate(Request $request)
        {
            $credentials = $request->only('email', 'password');       
            try{
                if (! \Auth::once($credentials)){                
                        return response()->json(['error' => 'invalid_credentials'], 401);
                    }else{
                        $user = \Auth::user();
                        $customClaims = ['utype' => $user->getUserType()];
                        $token = JWTAuth::fromUser($user, $customClaims);
                    }
        ...
    

    所以你必须在模型类(User.php)中定义一个getUserType(),或者直接从AuthenticateController中的$user对象中获取userType。然后使用JWTAuth::fromUser,如creating a token based on a user object 部分所述。

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2017-02-08
      • 2017-10-24
      • 2019-10-29
      • 2018-11-18
      • 2018-09-15
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多