VSCode+.Net Core 2.0 WebAPI JWT身份验证

一、使用VSCode 创建WebApi

1、在官网下载 VSCode以及dotnet-sdk-2.1的安装包(本人为windows64)

2、安装包安装完成后,启动VSCode,使用dotnet 命令 dotnet new webapi 创建一个webAPi项目

二、appsettings.json 配置JWT基础信息

1、JWT 官网 https://jwt.io

2、webapi 项目创建完成后,打开文件appsettings.json文件,添加下面的配置

"JwtSettings":{

"Issuer":"http://localhost:5000",

"Audience":"http://localhost:5000",

"SecretKey":"Hello-key-----wyt"

}

此处的配置分别为JWT口令签发人、口令接收人、秘钥key

2、项目中创建JwtSettings.cs

using System;



namespace DotNet.Utilities

{

///

///JWT配置信息

///

public class JwtSettings

{

//token是谁颁发的

public string Issuer { get; set; }

//token可以给哪些客户端使用

public string Audience { get; set; }

//加密的key

public string SecretKey{get;set;}



}

}

三、Startup.cs 文件配置注册身份认证

1、在创建的webapi csproj文件中添加如下引用







2、首先在Startup.cs文件中添加如下引用

using System.Text;

using Microsoft.AspNetCore.Authorization;

using Microsoft .AspNetCore.Authentication.JwtBearer;

using Microsoft.IdentityModel.Tokens;

3、在ConfigureServices方法中写如下代码:

public void ConfigureServices(IServiceCollection services)

{



#region "JWT"

//Get JwtSettings from appsettings.json

services.Configure(Configuration.GetSection("JwtSettings"));

// assign JwtSettings model

var jwtSettings=new JwtSettings();

Configuration.Bind("JwtSettings",jwtSettings);



services.AddAuthentication(options=>{

//Auth middleware config

options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;

options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(o=>{

// set jwt token parameters

o.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{

ValidIssuer =jwtSettings.Issuer,//Issuer

ValidAudience =jwtSettings.Audience,//Audience

//Encryption secret key

IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),

ValidateIssuer = true, //whether or not valid Issuer

ValidateAudience = true, //whether or not valid Audience

ValidateLifetime = true, //whether or not valid out-of-service time

ValidateIssuerSigningKey = true, //whether or not valid SecurityKey           

           ClockSkew=TimeSpan.Zero//Allowed server time offset

};

});

#endregion

services.AddMvc();

}

4、在Configure方法中添加

app.UseAuthentication();

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

app.UseAuthentication();

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseMvc();

}

四、创建生成Token的controller

1、创建TokenController.cs文件,用于生成Token时调用此请求,代码如下:

[Route("api/[controller]")]

/// 

/// Token

/// 

public class TokenController : Controller

{

private JwtSettings _jwtSettings;

JWtToken jwttoken = new JWtToken();



private HttpResponseMessage WriteMsg(string Msg)

{

return new HttpResponseMessage { Content = new StringContent(Msg, System.Text.Encoding.UTF8, "application/json") };

}

/// 

/// 构造方法

/// 

/// Token Model

public TokenController(IOptions _jwtSettingsAccesser)

{

_jwtSettings = _jwtSettingsAccesser.Value;

}



///

///生成Token

///

///登录信息

///

[HttpPost]

[Route("CreateToken")]

public ActionResult CreateToken([FromBody] LoginInfo Loginuser)

{

string strResult = "";

//判断用户是否存在

List userlist =UserinfoBLL.Login(Loginuser.UserName,Loginuser.PassWord);

if (userlist != null)

{

//用户唯一 返回口令

if (userlist.Count == 1)

{

jwttoken.Token = MakeToken(userlist[0]);

strResult=RequestReturn.ReturnInfo("","",jwttoken).ToString();

}

//用户不唯一

if (userlist.Count > 1)

{

strResult=RequestReturn.ReturnInfo("00002","用户不唯一,请联系管理员","").ToString();

}

}

else

{

strResult=RequestReturn.ReturnInfo("00001","用户名或密码错误","").ToString();

}

return Content(strResult);

}



/// 

/// MakeToken

/// 

/// 用户Model

/// Token

private string MakeToken(UserInfo item)

{

string strToken = "";

var claim = new Claim[]{

new Claim(ClaimTypes.Name,item.UserName),

new Claim(ClaimTypes.Role,item.RoleID),

new Claim("UserTrueName",item.UserTrueName),

new Claim("UserID",item.UserID)

};

//对称秘钥

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));

//签名证书(秘钥,加密算法)

var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

//生成token [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间

var token = new JwtSecurityToken

(

issuer: _jwtSettings.Issuer,

audience: _jwtSettings.Audience,

claims: claim,

notBefore: DateTime.Now,

expires: DateTime.Now.AddHours(2),//过期时间

signingCredentials: creds

);

try

{

//生成口令

strToken = new JwtSecurityTokenHandler().WriteToken(token);

}

catch

{



}

return strToken;

}



/// 

/// 用户登录信息

/// 

public class LoginInfo

{

/// 

/// 登录名

/// 

public string UserName { get; set; }

/// 

/// 登录密码

/// 

public string PassWord { get; set; }

}



}

五、JWT身份验证使用测试

1、我这边创建一个用于获取用户信息的controller文件,添加[Authorize]

///

///获取用户列表

///

[HttpGet]

[Authorize]

[Route("GetAllList")]

public ActionResult GetAllList()

{

string strResult = "";

List userlist= new List();

userlist=UserinfoBLL.GetALLList();

if (userlist != null)

{

strResult = RequestReturn.ReturnInfo("", "", userlist).ToString();

}

else

{

strResult = RequestReturn.ReturnInfo("00003", "无数据", "").ToString();

}

return Content(strResult);

}

2、使用Potman,先获取生成的token命令,再将Token从headers传入,进行身份验证,若Token验证失败,则无法获取任何信息

你可能感兴趣的:(.Net,webApi,C#)