Satellizer JWT令牌将用户信息添加到有效负载

时间:2016-01-27 00:46:23

标签: angularjs laravel jwt

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

这是我的Auth控制器

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

}

})();

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

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

1 个答案:

答案 0 :(得分:0)

有效负载在后端(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(),或直接从userType中的$user对象获取AuthenticateController。然后使用JWTAuth::fromUser部分中所述的{{1}}。