我如何发送授权信息回我的客户端应用程序中使用AngularJS,2的WebAPI和OAuth 2时? [英] How can I send authorization information back to my client app when using AngularJS, WebAPI 2 and Oauth 2?

查看:136
本文介绍了我如何发送授权信息回我的客户端应用程序中使用AngularJS,2的WebAPI和OAuth 2时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 JavaScript中的 AngularJS 客户端应用程序(不CoffeeScript的或打字稿)的OAuth2反对一个验证的WebAPI 2 采用了最新的身份2应用。在我的应用程序的所有软件是最新的,并且基于<一个href=\"http://www.$c$cproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En\"><$c$c>this例如 。我的客户端浏览器目标是IE9以上。

I have a AngularJS client application that uses javascript (not coffeescript or typescript) Oauth2 to authenticate against a WebAPI 2 application using the latest Identity 2. All the software in my application is the very latest and is based on this example. My client browser targets are IE9 and above.

请注意,我把上面,我不urlen code全部采用向服务器发送的数据的变换从例子中一些细微的变化。相反,我urlen code只能在下面的authenticate方法:

Note that I made some minor changes from the example above in that I do not urlencode all of the data sent to the server using the transform. Instead I urlencode only in the authenticate method below:

user.authenticate = function (userName, password, rememberMe, successCallback, errorCallback) {
    var config = {
        method: 'POST',
        url: '/Token',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
    };

我与VS2013 Update 2和服务器上搞开发,我使用C#,最新的实体框架和SQL Server 2012。

I am developing with VS2013 Update 2 and on the server, I use C#, the latest Entity Framework and SQL Server 2012.

要登录我的客户端调用/令牌方法将的WebAPI并传递用户名和密码。该的WebAPI然后用令牌,我在客户端存储响应。对于每个请求的WebAPI令牌发送回和认证:

To login my client calls a /Token method to the WebAPI and passes the userid and password. The WebAPI then responds with a token to the client which I store. With each request to the WebAPI the token is sent back and authenticated:

$http.defaults.headers.common.Authorization = 'Bearer ' + user.data.bearerToken;

这工作得很好,到目前为止,但因为它代表应用程序无法告诉分配有不同角色的用户之间的差异。

This works very well so far but as it stands the application is unable to tell the difference between users that have different roles assigned to them.

一些的WebAPI方法只能通过谁有一定的作用的用户执行。我想调整我的前端应用AngularJS的菜单,使只有当用户有这个角色那么适当的链接将显示可见。我也知道这不会从检查HTML和发布停止一个用户,但我不关心这个,因为我仍然有办法的装饰来限制用户不是在一个角色来执行操作的能力。

Some of the WebAPI methods can only be executed by users who have a certain role. I would like to adjust the menus of my front-end AngularJS application so that only if the user has this role then the appropriate links will appear visible. I do realize that this would not stop a user from checking the HTML and posting but I am not concerned about this as I will still have method decoration to limit the ability of users not in a role to perform actions.

能有人给我的,我怎么能做到这一点使用的只是上面提到的产品套件为例,我提的问题以及JavaScript的网页令牌,如果他们帮助把解决方案最新。从我所理解的角色被要求处理,但我不知道如何添加这些,并将它们发送回客户端用令牌。我已经做了很多的研究在互联网上,但我没能找到任何很好的例子,因为我认为大部分是很新的,而不是很多人都有过探索SPA如何使用这些最新软件的机会组件。

Can someone give me an example of how I can do this using just the suite of products mentioned above that I mention in the question plus JavaScript Web Tokens if they help make bring the solution up to date. From what I understand roles are handled by claims but I do not understand how to add these and send them back to the client with tokens. I have done a lot of research on the internet but I've not been able to find any good examples as I think most of this is very new and not many people have had the chance to explore how a SPA can use these very latest software components.

在回答这个问题时,请注意我不是寻找一个答案,它可以告诉社会如何建立角色的服务器或说明它是多么的重要,提供角色的答案上在服务器上检查。我想几乎所有人都意识到了这一点。我真的认为将是利用与样品code和解释一些非常详细的技术建议。为了保持专注答案它可能会帮助大家,如果不符合这种需求的答案不公布所建议的答案。

When answering this question please note that I am not looking for an answer that can tell the community how to set up roles on the server or an answer that explains about how important it is to provide role checks on the server. I think almost everyone is aware of this. What I really think will be of use is some very detailed technical suggestions with sample code and an explanation. To keep the answer focused it would probably be of help to everyone if answers that do not meet this need are not posted as suggested answers.

感谢您提前。

推荐答案

简短的回答你的问题是 ApplicationOAuthProvider.CreateProperties 方法。它在默认情况下为您创建,并在被发现的 WebApi2 /供应商/ ApplicationOAuthProvider.cs 后,默认情况下,只发送的userName

The short answer to your question is ApplicationOAuthProvider.CreateProperties method. Its created for you by default and is found under WebApi2/Provider/ApplicationOAuthProvider.cs, By default it only sends the userName

//WepApi2/Providers/ApplicationOAuthProvider.cs
public static AuthenticationProperties CreateProperties(string userName)
{
    IDictionary<string, string> data = new Dictionary<string, string>
    {
        { "userName", userName }
    };
    return new AuthenticationProperties(data);
}

我会做以下更新(如果我需要发送以后更多的用户数据):

I would make the following update (in case I need to send more user data later on):

public static AuthenticationProperties CreateProperties(string userName, ClaimsIdentity oAuthIdentity)
{ 
  IDictionary<string, string> data = new Dictionary<string, string>
  {
      { "userName", userName},
      { "roles",string.Join(",",oAuthIdentity.Claims.Where(c=> c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray())}

  };
  return new AuthenticationProperties(data);
}

如果你还没有到的WebAPI项目发生重大变化, ApplicationOAuthProvider.CreateProperties 只在两个地方引用,只需更新调用code传递 oAuthIdentity user.UserName 一起,你会得到的访问令牌响应一起发送的用户角色:

If you haven't made major changes to the WebApi project, ApplicationOAuthProvider.CreateProperties is only referenced in two places, just update the calling code to pass the oAuthIdentity along with user.UserName and you'll get the user roles sent along with the access token response:

{
 "access_token": "ZpxAZyYuvCaWgShUz0c_XDLFqpbC0-DIeXl_tuFbr11G-5hzBzSUxFNwNPahsasBD9t6mDDJGHcuEqdvtBT4kDNQXFcjWYvFP7U2Y0EvLS3yejdSvUrh2v1N7Ntz80WKe5G_wy2t11eT0l48dgdyak8lYcl3Nx8D0cgwlQm-pePIanYZatdPFP9q5jzhD-_k9SF-ARTHgf0ePnbvhLBi1MCYQjvfgPKlbBHt0M5qjwGAeFg1IhSVj0gb4g9QTXoiPhRmxGBmjOpGgzxXixavmrpM7cCBFLoR3DCGnIJo6pwT-6VArxlB8-ZyyOZqh_6gGtptd0lIu8iJRUIGwO9HFNkROdoE9T4buwLnhPpWpy9geBjPVwsB1K3xnbch26YbklhxIHVybBxeIVXd17QTw_LjlQ5TJdqpAYfiZ5B9Nx2AFYYYe3--aemh4y1XOIvN",
 "token_type": "bearer",
 "expires_in": 1209599,
 "userName": "MK",
 "roles": "Admin,Public",
 ".issued": "Fri, 23 May 2014 17:36:54 GMT",
 ".expires": "Fri, 06 Jun 2014 17:36:54 GMT"
}

现在你有角色可用,您可以用角条件指令显示/根据用户角色隐藏的行动。

Now you have the roles available, you can use Angular conditional directives to show/hide actions according to user roles.

如果你需要进一步澄清,请让我知道。

If you need more clarification, please let me know.

编辑:

装饰你的控制器方法授权属性是有效的,因为 HttpContext.Current.User.Identity 实际上是一个 ClaimsIdentity 。但不会在应用程序内硬code安全逻辑,我使用preFER <一个href=\"http://msdn.microsoft.com/en-us/library/system.security.claims.claimsauthorizationmanager.checkaccess%28v=vs.110%29.aspx\"><$c$c>ClaimsAuthorizationManager

Decorating your controller methods with Authorize attribute is valid, since the HttpContext.Current.User.Identity is actually a ClaimsIdentity. But as not to hard code security logic inside the application, I prefer using ClaimsAuthorizationManager

public ActionResult Secure()
{
  if(!ClaimsPrincipalPermission.CheckAccess("resource", "action"))
    return new HttpUnauthorizedResult();

  ViewBag.Message = "You are allowed to perform action on resource.";
  return View();
}

使用

角色创建 RoleManager

RoleManager roleManger = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
roleManager.Create(new IdentityRole() { Name = "Admin" });

角色分配使用的UserManager

userManager.AddToRole(user.Id, "Admin");

这篇关于我如何发送授权信息回我的客户端应用程序中使用AngularJS,2的WebAPI和OAuth 2时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆