在ASP.NET Core中实现一个Token base的身份认证实例_实用技巧

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

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

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

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

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

前期准备

推荐使用VS2015 Update3作为你的IDE,下载地址:http://www.jb51.net/softjc/446184.html

你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:http://www.jb51.net/softs/472362.html

创建项目

在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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索asp.net
, token
, core
token验证
,以便于您获取更多的相关知识。

时间: 2024-10-03 11:06:03

在ASP.NET Core中实现一个Token base的身份认证实例_实用技巧的相关文章

ASP.NET Core 数据保护(Data Protection 集群场景)下篇_实用技巧

前言  接[中篇] ,在有一些场景下,我们需要对 ASP.NET Core 的加密方法进行扩展,来适应我们的需求,这个时候就需要使用到了一些 Core 提供的高级的功能.  本文还列举了在集群场景下,有时候我们需要实现自己的一些方法来对Data Protection进行分布式配置.  加密扩展  IAuthenticatedEncryptor 和 IAuthenticatedEncryptorDescriptor  IAuthenticatedEncryptor是 Data Protection

asp.net SAF 中缓存服务的实现第1/5页_实用技巧

复制代码 代码如下: protected void Page_Load(object sender, EventArgs e)     {         webinfo info = new webinfo();         Response.Write("有static的执行结果:" + webinfo.a + "<br />");         Response.Write("没有static的执行结果:" + info.

ASP.NET框架中的数据绑定概要与数据绑定表达式的使用_实用技巧

<%# %> 语法 ASP.NET 介绍了一种新的声明性语法 <%# %>.该语法是在 .aspx 页中使用数据绑定的基础.所有数据绑定表达式都必须包含在这些字符中.下面的列表包含从多个源进行简单数据绑定的示例: 简单属性(用于客户的语法): <%# custID %> 集合(用于订单的语法): <asp:ListBox id="List1" datasource='<%# myArray %>' runat="serve

asp.net开发中常见公共捕获异常方式总结(附源码)_实用技巧

本文实例总结了asp.net开发中常见公共捕获异常方式.分享给大家供大家参考,具体如下: 前言:在实际开发过程中,对于一个应用系统来说,应该有自己的一套成熟的异常处理框架,这样当异常发生时,也能得到统一的处理风格,将异常信息优雅地反馈给开发人员和用户.我们都知道,.net的异常处理是按照"异常链"的方式从底层向高层逐层抛出,如果不能尽可能地早判断异常发生的边界并捕获异常,CLR会自动帮我们处理,但是这样系统的开销是非常大的,所以异常处理的一个重要原则是"早发现早抛出早处理&q

ASP.NET编程中经常用到的27个函数集_实用技巧

ASP.Net是建立在微软新一代.Net平台架构上,利用普通语言运行时(Common Language Runtime)在服务器后端为用户提供建立强大的企业级Web应用服务的编程框架.下面列举了常用的27个ASP.NET中的函数集: 1.DateTime 数字型 复制代码 代码如下: System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.DateTime.Now; 1.2 取当前年

asp.net URL中包含中文参数造成乱码的解决方法_实用技巧

问题: 前段时间,在系统中做了一个类似于友情链接的功能块,一直运行良好,直到有一天加了类似于以下的链接地址:http://www.****.com/user.aspx?id=水天,就出现大问题了: 1.从IE地址栏中直接输入这个地址,访问没错: 2.做一个静态页,其中包括这个超链接,点击访问也没错: 3.就是把这个链接添加到这个功能块中,点击访问那边接收到的是乱码. 一开始,被这个问题也搞得头大,在google了一把后,总算是把问题给搞清楚了,其实只要这个链接地址不经过任何编码传递是不会有问题的

ASP.NET MVC中URL地址传参的两种写法_实用技巧

一.url地址传参的第一种写法 1.通过mvc中默认的url地址书写格式:控制器/方法名/参数 2.实例:http://localhost:39270/RequestDemo/Index/88,默认参数名为id所以名称为id. 如果使用其他名称,后台是无法读取的会报错 二.url地址传参的第二种写法 1.使用?加参数名=参数值的写法,如果有多个参数使用&来连接 http://localhost:39270/RequestDemo/Index?id=88&name=%E5%BC%A0%E4%

ASP.NET(C#) Web Api通过文件流下载文件的实例_实用技巧

下载文件到本地是很多项目开发中需要实现的一个很简单的功能.说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是ASP.NET Web Api方式返回HttpResponseMessage下载文件到本地.实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的HttpResponseMessage的Content.直接贴出DownloadController控件器的代码: using System; using System.Collections.

asp.net继承IHttpHandler接口实现给网站图片添加水印功能实例_实用技巧

本文实例讲述了asp.net继承IHttpHandler接口实现给网站图片添加水印功能.分享给大家供大家参考,具体如下: 先展示图片效果: 1. 在App_Code下添加类文件,命名为ImageSY 文件内容如下 public class ImageSY : IHttpHandler { public ImageSY() { // //TODO: 在此处添加构造函数逻辑 // } #region IHttpHandler 成员 public bool IsReusable { get { ret