使用AngularJs,WebAPI和OAuth2时,获得带有JWT的明文用户角色 [英] Get user role in clear text along with JWT when using AngularJs, WebAPI and OAuth2
问题描述
我正在WebAPI项目中唱歌OAuth2.我正在OWIN中间件中验证用户请求.身份验证成功后,我将向客户端发送JWT访问令牌.现在,我可以在服务器上验证后续请求,并在Api控制器上使用[Authorize(Roles ="myRole")]属性.
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.
但是我该如何在AngularJs中显示验证客户端内容并根据用户角色显示页面?我在客户端上有JWT,不知道如何从中获得用户角色?
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?
从JWT中提取信息是一种好方法吗?
Is it a good approach to extract information from JWT?
推荐答案
您将需要解析该JWT并获取值.您可以借助angular-jtw库来做到这一点.
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)下载angular-jwt.min.js( https://github.com/auth0 /angular-jwt )
1) Download the angular-jwt.min.js (https://github.com/auth0/angular-jwt)
2)在应用程序模块上放置"angular-jwt"的依赖项:
2) put a dependecy of "angular-jwt" on the application module:
var app = angular.module("YOUR_APP", ["angular-jwt"]);
3)将jwtHelper传递给您的服务或控制器,或者将其传递到您希望使用它的任何地方.
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)使用传入的jwtHelper的decodeToken方法对令牌进行解码
4) use the decodeToken method of the jwtHelper you passed in to decode your token
例如,下面的代码正在从服务端点返回的jwt中解析角色对象.从服务器成功返回后,将从jwt中提取角色并返回.
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;
});
};
希望有帮助
//胡迪尼
这篇关于使用AngularJs,WebAPI和OAuth2时,获得带有JWT的明文用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!