身份验证方法是在asp.net的Web API和角JS使用 [英] Authentication approach to be use in asp.net Web api and angular js

查看:139
本文介绍了身份验证方法是在asp.net的Web API和角JS使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用网络API和角的js 创建1个网站,我如此多的困惑在我的网站上使用的验证。

I am creating 1 website using Web api and angular js and i am so much confused about Authentication to be used in my web site.

我已创建了一个 login.js 中会有我的登录方法,会后我的用户名/ EMAILID和密码到我的网页API,并在网页API的方法就可以验证该用户。

I have created one login.js in which there would be my Login method which will post my Username/Emailid and password to my Web Api and the method in web api will authenticate that user.

code:

$scope.Login()
{
  $.post("api/Authentication/Login",Username,Password)
  {
  }
}

网页API code:

Web api code:

[Route]
Public Task<object> Login([FromBody] username,password)
{
   //method to authenticate user from database.
   //Now the tricky parts comes like after authenticating user should i 
   //just store the user id in my session like this Session["userid]=id or
   //Should i go for storing whole user object in my cookie as i have read 
   //that storing data in session is very bad idea and disaster too as session is very memory
   //and so i think i would go for cookie which will be saved on client side.
   //but what if cookie isnt supported by browser??
}

使用会话灾难是由达林季米特洛夫指出了他的回答和评论
所以我决定使用cookie的按照这个答案和电子商务网站,是 NOP商务部的人使用过的cookie存储当前登录的客户对象,按这个问题,回答<一个href=\"http://www.nopcommerce.com/boards/t/40378/why-nop-commerce-uses-cookie-to-store-currently-login-customer-object.aspx.\"相对=nofollow>问题

Using session is disaster as pointed out by Darin Dimitrov in his answer and comments. So i have decided to use cookie as per this answer and one of the ecommerce site that is Nop Commerce uses cookie too to store currently login customer object as per this question and answer Question

我按照这样code在这个<一个由 LukeP 建议href=\"http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal\">Question认证的目的和保持在我的整个appilcation currenlty登录用户对象。

I am following this code suggested by LukeP in this Question for authentication purpose and maintaining currenlty login user object across my whole appilcation.

我看了一下asp.net声明身份太多,但不知道我是否能在我的asp.net网页API和角JS使用它。

I have read about asp.net claim identity too but dont know whether i can use it in my asp.net web api and angular js.

所以有谁能够告诉我什么是正确的方法使用在asp.net网页API和角度JS验证和什么都改变到的 LukeP code。与网页API和角JS ??工作

So can anybody tell me whats the correct approach to use for authentication in asp.net web api and angular js and what all the changes to be done in LukeP code to work with web api and angular js??

谁能给我解释一下这个appraoch我已经指出上述用一些细节的描述和一些codeS太多,因为它可以帮助我和其他一些人太多,如果他们正在寻找相同的。

Can anybody explain me about this appraoch which i have pointed above with some detail description and some codes too as it can help me and some others too if they are searching for the same.

我将在稍后提供的 100赏金答案解决所有上述的一些codeS的关注。

推荐答案

要做到这一点,最好的办法是用令牌认证。总之它的工作原理是这样的:

The best way to do it is with token authentication. In summary it works like this:


  • A POST / API /登录在服务器上的路由发生在一个用户名+密码,检查他们对数据库有效,然后生成并返回刷新标记(这可以只是一个随机字符串或GUID)。在刷新标记也存储在旁边的用户数据库,覆盖previous 刷新标记

  • 在服务器上
  • A GET / API /访问令牌路由发生在一个用户名+ 刷新标记,支票他们匹配数据库中,然后生成并返回一个访问令牌

  • 任何其他 / API / * 路线需要一个有效的访问令牌是在请求的头,否则假设用户没有一个有效的登录

  • A POST /api/login route on the server takes in a username + password, checks that they are valid against the database, then generates and returns a refresh token (which can just be a random string or GUID). The refresh token is also stored in the database next to the user, overwriting the previous refresh token
  • A GET /api/access-token route on the server takes in a username + refresh token, checks that they match in the database, then generates and returns an access token
  • Any other /api/* routes require a valid access token to be in the header of the request, otherwise they assume the user does not have a valid login

访问令牌是已使用只有服务器知道一个秘密密钥加密的数据对象。它应该包含用户名,失效日期(通常〜从生成的令牌时10分钟),以及任何权限或有关用户的其它数据。因为它是用密钥加密的,它不能被攻击者伪造的

The access token is a data object that has been encrypted using a secret key that only the server knows. It should contain the username, an expiry date (usually ~10mins from when the token was generated), and any permissions or misc data about the user. Because it is encrypted with a secret key, it cannot be forged by an attacker.

您将需要在服务器上实施这些路由。

You will need to implement these routes on your server.

如果您使用的是OWIN,这里是你如何使用 Microsoft.Owin.Security.OAuth 的NuGet包做加密位为您提供:

If you are using OWIN, here is how you can use the Microsoft.Owin.Security.OAuth NuGet package to do the encryption bit for you:

有这:

using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;

[assembly: OwinStartup(typeof(MyProject.Startup))]
namespace MyProject
{
    public class Startup
    {
        public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            app.UseWebApi(config);
        }
    }
}

然后,您可以生成一个门票(这是未加密的访问令牌),并像这样对它进行加密:

Then, you can generate a ticket (which is the unencrypted access token) and encrypt it like this:

var identity = new ClaimsIdentity(new[] {
    new Claim(ClaimTypes.Email, "users email"),
    // other business specific claims e.g. "IsAdmin"
});
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties(
    {
        ExpiresUtc = DateTime.UtcNow.AddMinutes(10)
    }));
var accessToken = MyProject.Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

在角你需要设置的方式登录,一种方式来获得一个新的访问令牌时到期,和一种方式来传递访问令牌在每一个API请求的报头。我建议存储刷新标记访问令牌在本地存储(或饼干旧的浏览器),并使用 $ httpProvider.interceptors.push 添加一个拦截器,每 $ HTTP 电话。然后拦截器可以访问令牌添加到像这样的标题: config.headers ['授权'] ='承载'+的accessToken;

In Angular you need to setup a way to login, a way to get a new access token when it expires, and a way to pass the access token in the header of every API request. I recommend storing the refresh token and access token in local storage (or cookie for old browsers), and using $httpProvider.interceptors.push to add an interceptor for every $http call. The interceptor can then add the access token to the header like this: config.headers['Authorization'] = 'Bearer ' + accessToken;

在定义角拦截器:

angular.module('app').service('authenticationInterceptor', ['$q', function($q) {
    this.request = function(config) {
        var accessToken = // ... get the access token from local storage / cookie
        config.headers['Authorization'] = 'Bearer ' + accessToken;
        return config;
    };
}]);

将它添加到 $ httpProvider

angular.module('app').config(['$httpProvider', ($httpProvider: ng.IHttpProvider) => {
    $httpProvider.interceptors.push('authenticationInterceptor');
}]);

这篇关于身份验证方法是在asp.net的Web API和角JS使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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