编程语言
首页 > 编程语言> > c# – 在asp.net Web api和angular js中使用的身份验证方法

c# – 在asp.net Web api和angular js中使用的身份验证方法

作者:互联网

我正在使用Web api和angular js创建一个网站,我对我的网站中使用的身份验证非常困惑.

我创建了一个login.js,其中有我的Login方法,它将我的用户名/ Emailid和密码发布到我的Web Api,web api中的方法将验证该用户.

码:

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

Web api代码:

[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??
}

使用会话是灾难,正如Darin Dimitrov在他的回答和评论中指出的那样.
所以我决定按照这个答案使用cookie,其中一个电子商务网站Nop Commerce使用cookie来存储当前登录的客户对象,根据这个问题和答案Question

我遵循LukeP在此Question中建议的此代码,用于身份验证,并在整个应用程序中维护当前的登录用户对象.

我也读过关于asp.net声明身份但不知道我是否可以在我的asp.net web api和angular js中使用它.

所以有人能告诉我在asp.net web api和angular js中使用正确的身份验证方法以及在LukeP代码中使用web api和angular js进行的所有更改吗?

任何人都可以向我解释这个appraoch,我已经在上面提到了一些细节描述和一些代码,因为它可以帮助我和其他一些人,如果他们正在寻找相同的.

稍后我将提供100点赏金,以解决上述一些代码的问题.

解决方法:

最好的方法是使用令牌身份验证.总之,它的工作原理如下:

>服务器上的POST / api /登录路由接收用户名密码,检查它们对数据库是否有效,然后生成并返回刷新令牌(可以是随机字符串或GUID).刷新令牌也存储在用户旁边的数据库中,覆盖先前的刷新令牌
>服务器上的GET / api / access-token路由接收用户名刷新令牌,检查它们在数据库中是否匹配,然后生成并返回访问令牌
>任何其他/ api / *路由都要求有效的访问令牌位于请求的标头中,否则它们会假定用户没有有效的登录名

访问令牌是使用仅服务器知道的密钥加密的数据对象.它应该包含用户名,到期日期(通常从生成令牌起约10分钟),以及有关用户的任何权限或misc数据.因为它是使用密钥加密的,所以攻击者无法伪造它.

您需要在服务器上实现这些路由.

如果您正在使用OWIN,以下是如何使用Microsoft.Owin.Security.OAuth NuGet包为您执行加密位:

在你的启动配置中有这个:

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);
        }
    }
}

然后,您可以生成一个票证(这是未加密的访问令牌)并加密它,如下所示:

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);

在Angular中,您需要设置一种登录方式,一种在到期时获取新访问令牌的方法,以及在每个API请求的标头中传递访问令牌的方法.我建议将刷新令牌和访问令牌存储在本地存储(或旧浏览器的cookie)中,并使用$httpProvider.interceptors.push为每个$http调用添加拦截器.然后,拦截器可以将访问令牌添加到头部,如下所示: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');
}]);

标签:c,angularjs,asp-net-web-api,form-authentication,nopcommerce
来源: https://codeday.me/bug/20190611/1220141.html