Get user role in clear text along with JWT when using AngularJs, WebAPI and OAuth2

送分小仙女□ 提交于 2019-12-11 02:16:30

问题


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.



来源:https://stackoverflow.com/questions/29271314/get-user-role-in-clear-text-along-with-jwt-when-using-angularjs-webapi-and-oaut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!