以前在web端的身份认证都是基于Cookie | Session的身份认证, 在没有更多的终端出现之前,这样做也没有什么问题,但在Web API时代,你所需要面对的就不止是浏览器了,还有各种客户端,这样就有了一个问题,这些客户端是不知道cookie是什么鬼的。 (cookie其实是浏览器搞出来的小猫腻,用来保持会话的,但HTTP本身是无状态的, 各种客户端能提供的无非也就是HTTP操作的API)
而基于Token的身份认证就是应对这种变化而生的,它更开放,安全性也更高。
基于Token的身份认证有很多种实现方式,但我们这里只使用微软提供的API。
接下来的例子将带领大家完成一个使用微软JwtSecurityTokenHandler完成一个基于beare token的身份认证。
注意:这种文章属于Step by step教程,跟着做才不至于看晕,下载完整代码分析代码结构才有意义。
前期准备
推荐使用VS2015 Update3作为你的IDE,下载地址:http://www.weikejianghu.com/softjc/446184.html
你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:http://www.weikejianghu.com/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);
}
}
}
}
</div>
在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);
}
}
</div>
Startup.cs
在ConfigureServices中添加如下代码:
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
</div>
完整的代码应该是这样
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();
}
</div>
在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();
});
});
</div>
这段代码主要是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();
});
});
</div>
应用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)
}
});
</div>
完整的代码应该是这样
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 fr

