NET Core中实现一个Token base的身份认证

注:本文提到的代码示例下载地址> How to achieve a bearer token authentication and authorization in ASP.NET Core

在ASP.NET Core中实现一个Token base的身份认证

以前在web端的身份认证都是基于Cookie | Session的身份认证, 在没有更多的终端出现之前,这样做也没有什么问题,
但在Web API时代,你所需要面对的就不止是浏览器了,还有各种客户端,这样就有了一个问题,这些客户端是不知道cookie是什么鬼的。 (cookie其实是浏览器搞出来的小猫腻,用来保持会话的,但HTTP本身是无状态的, 各种客户端能提供的无非也就是HTTP操作的API)

而基于Token的身份认证就是应对这种变化而生的,它更开放,安全性也更高。

基于Token的身份认证有很多种实现方式,但我们这里只使用微软提供的API。

接下来的例子将带领大家完成一个使用微软JwtSecurityTokenHandler完成一个基于beare token的身份认证。

注意:这种文章属于Step by step教程,跟着做才不至于看晕,下载完整代码分析代码结构才有意义。

前期准备

创建项目

在VS中新建项目,项目类型选择ASP.NET Core Web Application(.NET Core), 输入项目名称为CSTokenBaseAuth

Coding

  • 创建一些辅助类

    在项目根目录下创建一个文件夹Auth,并添加RSAKeyHelper.cs以及TokenAuthOption.cs两个文件

    • 在RSAKeyHelper.cs中

      using System.Security.Cryptography;
      
      namespace CSTokenBaseAuth.Auth
      {
      public class RSAKeyHelper
      {
      public static RSAParameters GenerateKey()
      {
      using (var key = new RSACryptoServiceProvider(2048))
      {
      return key.ExportParameters(true);
      }
      }
      }
      }
    • 在TokenAuthOption.cs中

      using System;
      using Microsoft.IdentityModel.Tokens; namespace CSTokenBaseAuth.Auth
      {
      public class TokenAuthOption
      {
      public static string Audience { get; } = "ExampleAudience";
      public static string Issuer { get; } = "ExampleIssuer";
      public static RsaSecurityKey Key { get; } = new RsaSecurityKey(RSAKeyHelper.GenerateKey());
      public static SigningCredentials SigningCredentials { get; } = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature); public static TimeSpan ExpiresSpan { get; } = TimeSpan.FromMinutes(20);
      }
      }
  • Startup.cs

    在ConfigureServices中添加如下代码:

    services.AddAuthorization(auth =>
    {
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
    .RequireAuthenticatedUser().Build());
    });

    完整的代码应该是这样

    public void ConfigureServices(IServiceCollection services)
    {
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);
    // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
    services.AddAuthorization(auth =>
    {
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
    .RequireAuthenticatedUser().Build());
    });
    services.AddMvc();
    }

    在Configure方法中添加如下代码

    app.UseExceptionHandler(appBuilder => {
    appBuilder.Use(async (context, next) => {
    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
    //when authorization has failed, should retrun a json message to client
    if (error != null && error.Error is SecurityTokenExpiredException)
    {
    context.Response.StatusCode = 401;
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { authenticated = false, tokenExpired = true }
    ));
    }
    //when orther error, retrun a error message json to client
    else if (error != null && error.Error != null)
    {
    context.Response.StatusCode = 500;
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { success = false, error = error.Error.Message }
    ));
    }
    //when no error, do next.
    else await next();
    });
    });

    这段代码主要是Handle Error用的,比如当身份认证失败的时候会抛出异常,而这里就是处理这个异常的。

    接下来在相同的方法中添加如下代码,

    app.UseExceptionHandler(appBuilder => {
    appBuilder.Use(async (context, next) => {
    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; //when authorization has failed, should retrun a json message to client
    if (error != null && error.Error is SecurityTokenExpiredException)
    {
    context.Response.StatusCode = 401;
    context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { authenticated = false, tokenExpired = true }
    ));
    }
    //when orther error, retrun a error message json to client
    else if (error != null && error.Error != null)
    {
    context.Response.StatusCode = 500;
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { success = false, error = error.Error.Message }
    ));
    }
    //when no error, do next.
    else await next();
    });
    });

    应用JwtBearerAuthentication

    app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
    IssuerSigningKey = TokenAuthOption.Key,
    ValidAudience = TokenAuthOption.Audience,
    ValidIssuer = TokenAuthOption.Issuer,
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.FromMinutes(0)
    }
    });

    完整的代码应该是这样

    using System;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using CSTokenBaseAuth.Auth;
    using Microsoft.AspNetCore.Diagnostics;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json; namespace CSTokenBaseAuth
    {
    public class Startup
    {
    public Startup(IHostingEnvironment env)
    {
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development"))
    {
    // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
    builder.AddApplicationInsightsSettings(developerMode: true);
    } builder.AddEnvironmentVariables();
    Configuration = builder.Build();
    } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration); // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
    services.AddAuthorization(auth =>
    {
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
    .RequireAuthenticatedUser().Build());
    }); services.AddMvc();
    } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); #region Handle Exception
    app.UseExceptionHandler(appBuilder => {
    appBuilder.Use(async (context, next) => {
    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; //when authorization has failed, should retrun a json message to client
    if (error != null && error.Error is SecurityTokenExpiredException)
    {
    context.Response.StatusCode = 401;
    context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { authenticated = false, tokenExpired = true }
    ));
    }
    //when orther error, retrun a error message json to client
    else if (error != null && error.Error != null)
    {
    context.Response.StatusCode = 500;
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(JsonConvert.SerializeObject(
    new { success = false, error = error.Error.Message }
    ));
    }
    //when no error, do next.
    else await next();
    });
    });
    #endregion #region UseJwtBearerAuthentication
    app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
    IssuerSigningKey = TokenAuthOption.Key,
    ValidAudience = TokenAuthOption.Audience,
    ValidIssuer = TokenAuthOption.Issuer,
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.FromMinutes(0)
    }
    });
    #endregion app.UseMvc(routes =>
    {
    routes.MapRoute(
    name: "default",
    template: "{controller=Login}/{action=Index}");
    });
    }
    }
    }
  • 在Controllers中新建一个Web API Controller Class,命名为TokenAuthController.cs。我们将在这里完成登录授权

    在同文件下添加两个类,分别用来模拟用户模型,以及用户存储,代码应该是这样

    public class User
    {
    public Guid ID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    } public static class UserStorage
    {
    public static List<User> Users { get; set; } = new List<User> {
    new User {ID=Guid.NewGuid(),Username="user1",Password = "user1psd" },
    new User {ID=Guid.NewGuid(),Username="user2",Password = "user2psd" },
    new User {ID=Guid.NewGuid(),Username="user3",Password = "user3psd" }
    };
    }

    接下来在TokenAuthController.cs中添加如下方法

    private string GenerateToken(User user, DateTime expires)
    {
    var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity(
    new GenericIdentity(user.Username, "TokenAuth"),
    new[] {
    new Claim("ID", user.ID.ToString())
    }
    ); var securityToken = handler.CreateToken(new SecurityTokenDescriptor
    {
    Issuer = TokenAuthOption.Issuer,
    Audience = TokenAuthOption.Audience,
    SigningCredentials = TokenAuthOption.SigningCredentials,
    Subject = identity,
    Expires = expires
    });
    return handler.WriteToken(securityToken);
    }

    该方法仅仅只是生成一个Auth Token,接下来我们来添加另外一个方法来调用它

    在相同文件中添加如下代码

    [HttpPost]
    public string GetAuthToken(User user)
    {
    var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password); if (existUser != null)
    {
    var requestAt = DateTime.Now;
    var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
    var token = GenerateToken(existUser, expiresIn); return JsonConvert.SerializeObject(new {
    stateCode = 1,
    requertAt = requestAt,
    expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
    accessToken = token
    });
    }
    else
    {
    return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
    }
    }

    该文件完整的代码应该是这样

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Security.Principal;
    using Microsoft.IdentityModel.Tokens;
    using CSTokenBaseAuth.Auth; namespace CSTokenBaseAuth.Controllers
    {
    [Route("api/[controller]")]
    public class TokenAuthController : Controller
    {
    [HttpPost]
    public string GetAuthToken(User user)
    {
    var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password); if (existUser != null)
    {
    var requestAt = DateTime.Now;
    var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
    var token = GenerateToken(existUser, expiresIn); return JsonConvert.SerializeObject(new {
    stateCode = 1,
    requertAt = requestAt,
    expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
    accessToken = token
    });
    }
    else
    {
    return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
    }
    } private string GenerateToken(User user, DateTime expires)
    {
    var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity(
    new GenericIdentity(user.Username, "TokenAuth"),
    new[] {
    new Claim("ID", user.ID.ToString())
    }
    ); var securityToken = handler.CreateToken(new SecurityTokenDescriptor
    {
    Issuer = TokenAuthOption.Issuer,
    Audience = TokenAuthOption.Audience,
    SigningCredentials = TokenAuthOption.SigningCredentials,
    Subject = identity,
    Expires = expires
    });
    return handler.WriteToken(securityToken);
    }
    } public class User
    {
    public Guid ID { get; set; } public string Username { get; set; } public string Password { get; set; }
    } public static class UserStorage
    {
    public static List<User> Users { get; set; } = new List<User> {
    new User {ID=Guid.NewGuid(),Username="user1",Password = "user1psd" },
    new User {ID=Guid.NewGuid(),Username="user2",Password = "user2psd" },
    new User {ID=Guid.NewGuid(),Username="user3",Password = "user3psd" }
    };
    }
    }
  • 接下来我们来完成授权验证部分

    在Controllers中新建一个Web API Controller Class,命名为ValuesController.cs

    在其中添加如下代码

    public string Get()
    {
    var claimsIdentity = User.Identity as ClaimsIdentity; var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value; return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}";
    }

    为方法添加装饰属性

    [HttpGet]
    [Authorize("Bearer")]

    完整的文件代码应该是这样

    using System.Linq;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Authorization;
    using System.Security.Claims; namespace CSTokenBaseAuth.Controllers
    {
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
    [HttpGet]
    [Authorize("Bearer")]
    public string Get()
    {
    var claimsIdentity = User.Identity as ClaimsIdentity; var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value; return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}";
    }
    }
    }
  • 最后让我们来添加视图

    在Controllers中新建一个Web Controller Class,命名为LoginController.cs

    其中的代码应该是这样

    using Microsoft.AspNetCore.Mvc;
    
    namespace CSTokenBaseAuth.Controllers
    {
    [Route("[controller]/[action]")]
    public class LoginController : Controller
    {
    public IActionResult Index()
    {
    return View();
    }
    }
    }

    在项目Views目录下新建一个名为Login的目录,并在其中新建一个Index.cshtml文件。

    代码应该是这个样子

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    </head>
    <body>
    <button id="getToken">getToken</button>
    <button id="requestAPI">requestAPI</button> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
    $(function () {
    var accessToken = undefined; $("#getToken").click(function () {
    $.post(
    "/api/TokenAuth",
    { Username: "user1", Password: "user1psd" },
    function (data) {
    console.log(data);
    if (data.stateCode == 1)
    {
    accessToken = data.accessToken; $.ajaxSetup({
    headers: { "Authorization": "Bearer " + accessToken }
    });
    }
    },
    "json"
    );
    }) $("#requestAPI").click(function () {
    $.get("/api/Values", {}, function (data) {
    alert(data);
    }, "text");
    })
    })
    </script>
    </body>
    </html>

最后:完整的代码Sample以及运行手册,请访问:How to achieve a bearer token authentication and authorization in ASP.NET Core

更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples

NET Core中实现一个Token base的身份认证的更多相关文章

  1. 在ASP.NET Core中实现一个Token base的身份认证

    注:本文提到的代码示例下载地址> How to achieve a bearer token authentication and authorization in ASP.NET Core 在 ...

  2. [转]NET Core中实现一个Token base的身份认证

    本文转自:http://www.cnblogs.com/Leo_wl/p/6077203.html 注:本文提到的代码示例下载地址> How to achieve a bearer token ...

  3. 如何在ASP.NET Core中实现一个基础的身份认证

    注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core 如何在ASP.NET Core中实现一个基础的身份认证 ...

  4. [转]如何在ASP.NET Core中实现一个基础的身份认证

    本文转自:http://www.cnblogs.com/onecodeonescript/p/6015512.html 注:本文提到的代码示例下载地址> How to achieve a bas ...

  5. ExpandoObject与DynamicObject的使用 RabbitMQ与.net core(一)安装 RabbitMQ与.net core(二)Producer与Exchange ASP.NET Core 2.1 : 十五.图解路由(2.1 or earler) .NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

    ExpandoObject与DynamicObject的使用   using ImpromptuInterface; using System; using System.Dynamic; names ...

  6. 在.NET Core中处理一个接口多个不同实现的依赖注入问题

    前言 近段时间在准备公司的技术分享,所以这段时间将大部分时间放在准备分享内容上去了.博客也就停了一下下. 在.NET Core中处理依赖注入问题时,往往是定义好了一个操作规范的接口,会有N多个基于不同 ...

  7. .NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

    最近有个需求就是一个抽象仓储层接口方法需要SqlServer以及Oracle两种实现方式,为了灵活我在依赖注入的时候把这两种实现都给注入进了依赖注入容器中,但是在服务调用的时候总是获取到最后注入的那个 ...

  8. 玩一玩基于Token的 自定义身份认证+权限管理

    使用基于 Token 的身份验证方法,在服务端不需要存储用户的登录记录.大概的流程是这样的: 客户端使用用户名跟密码请求登录 服务端收到请求,去验证用户名与密码 验证成功后,服务端会签发一个 Toke ...

  9. API网关设计(一)之Token多平台身份认证方案(转载)

    原文:https://segmentfault.com/a/1190000018535570?utm_source=tag-newest 概述 今天咱们面对移动互联网的发展,系统一般是多个客户端对应一 ...

随机推荐

  1. Guacamole之实现和架构(一)

    摘要 在网上看到一篇Guacamole官方手册的翻译,但是找不到后续,于是想自己也翻译几篇,有时间的话,会尽量多翻译一些.第一篇就直接转载过来了. Guacamole的介绍以及架构 Guacamole ...

  2. 实用技巧:使用 jQuery 异步加载 JavaScript 脚本

    JavaScript 加载器在 Web 开发中是非常强大和有用的工具.目前流行的几个加载器,像 curljs.LABjs 和 RequireJS 使用都很广泛.他们功能强大的,但有些情况下可以有更简单 ...

  3. ClockPicker – 时钟风格 Bootstrap 时间选择器

    ClockPicker 是国内前端开发者发布的一个时钟样式 Timepicker,可以用于 Bootstrap 和 jQuery.所有主流浏览器都支持,包括 IE9+,支持移动设备,能够在触摸屏设备很 ...

  4. HTML表单提交数据中application/x-www-form-urlencoded和multipart/form-data的区别

    在Form元素的语法中,EncType表明提交数据的格式 用 Enctype 属性指定将数据回发到服务器时浏览器使用的编码类型. 下边是说明: application/x-www-form-urlen ...

  5. javascript笔记图

    1.this 2.对象 3.继承 4.跨域 5.事件 6.基础

  6. iOS上new Date出现Invalid Date的问题,

    用angular的ngModel绑定time的时候,在安卓调试没问题,没想到在iOS上出现了NaN:NaN,后台丢过来的数据大概是这样的2016-03-08 20:14 然而问题就出在这个分隔符&qu ...

  7. [Dynamics CRM 2016]如何配置多语言显示

    1.安装相对应的语言包并安装 2015语言包下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=45014 2016语言包下载地 ...

  8. Iphone 英语语言下通讯录排序问题

    Iphone 如果把界面语言设置成English,那么通讯录默认排序是通过拼音来排的,如果联系人信息中没有设置名字的拼音,那么这些联系人都会被放到#中. 批量添加拼音的解决方案: https://gi ...

  9. This version of android studio is incompatible with the gradle version used.Try disabling the instant run解决办法

    今天打开android studio又碰到一个奇怪的问题:This version of android studio is incompatible with the gradle version ...

  10. MAVEN中的插件放在哪个dependcies里面

    如果你用maven来管理项目的话,你会发现你要依赖很多plugin,于是引出了一个问题. 一个project中可能有两个<dependcies>这个tag, 如下 <dependci ...