Get user role in clear text along with JWT when us

2019-07-21 04:29发布

问题:

I am sing OAuth2 in WebAPI project. I am authenticating user request in OWIN middleware. On successfull authentication I am sending an JWT access token to client. Now I can validate subsequent request at server and use [Authorize(Roles="myRole")] attribute on Api Controllers.

But how can I show validate client content in AngularJs and show pages based on user role? I have JWT at client and no idea how to get user role out of it?

Is it a good approach to extract information from JWT?

回答1:

You will need to parse that JWT and get the values out. You can do that with the help of the angular-jtw library.

1) Download the angular-jwt.min.js (https://github.com/auth0/angular-jwt)

2) put a dependecy of "angular-jwt" on the application module:

var app = angular.module("YOUR_APP", ["angular-jwt"]);

3) pass the jwtHelper to your service or controller or wherever it is that you wish to use it.

    app.module.factory("YOUR_SERVICE", function(jwtHelper){
    ...
});

4) use the decodeToken method of the jwtHelper you passed in to decode your token

For example, the code below is parsing out the role object from a jwt that came back from my service endpoint. Upon succssful return from the server the role is extracted from the jwt and returned.

return $http.post(serviceEndPoints.tokenUrl, data, config)
                    .then(function (response) {
                        var tokenPayLoad = jwtHelper.decodeToken(response.data.access_token);

//Now do whatever you wish with the value. Below I am passing it to a function: (determineRole)

                        var userRole = determineRoles(tokenPayLoad.role);


            return userRole;
        });
    };

Hope that helps

//Houdini



回答2:

Currently we don't offer anything that would help you to take advantage of that information on the client. Also note: as today we do not validate the token on the client, we cannot really trust its content... while the [Authorize] attribute on the server side gets the role info only after the pipeline before it had a chance of validating the signature and deciding that the token is valid. We might introduce something that will help with this scenario in the future, but for the time being you'd need to write custom code or rely on the server side to echo things back.