通过在请求的 Header 中添加如下 Header(注意 Bearer 后必须跟一个空格)
Authorization:Bearer [Access_Token]
添加JWT配置
修改 appsettings.json,添加如下节点,这里配置好了密钥用于JWT Token 的第三部分签名
"JWT":{ "SecurityKey":"ABCDEFGHIJKLMNOPQRSTUVWXYZ1456789513"},
修改 Startup.cs 注册 JWT
修改后的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法如下:
在这里添加了对验证的使用,注意调用UseAuthentication() 必须要在调用 UseMvc() 之前。
publicvoidConfigure(IApplicationBuilder app, IHostingEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
修改后的 ConfigureServices(IServiceCollection services) 方法
这里添加了一个 验证的处理方法,并且使用 JwtBearer 作为验证的处理,
publicvoidConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =newTokenValidationParameters
{
ValidateIssuer =true,
ValidateAudience =true,
ValidateLifetime =true,
ValidateIssuerSigningKey =true,
ValidIssuer ="lilibuy.com",
ValidAudience ="lilibuy.com",
IssuerSigningKey =newSymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecurityKey"]))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
增加认证以及 Token 给予
ValuesController里面把命名空间里面的全部删除 , 然后新加下面一段
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult
> Get() {
return new string[] { "value1", "value2" };
}
}
Token 给予
新建一个 OauthController,这个API Controller 类需要完成用户信息的比对以及如果比对结果显示这个是合法的用户,我们需要给用户返回 Token 信息。
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using asd.Models.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace asd.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
public class OauthController : Controller
{
public IConfiguration Configuration { get; }
public OauthController(IConfiguration configuration)
{
Configuration = configuration;
}
[HttpPost("authenticate")]
public IActionResult RequestToken([FromBody]TokenRequest request)
{
if (request != null)
{
//验证账号密码,这里只是为了demo,正式场景应该是与DB之类的数据源比对
if ("asdusername".Equals(request.UserName) && "userPassword123456".Equals(request.Password))
{
var claims = new[] {
//加入用户的名称
new Claim(ClaimTypes.Name,request.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var authTime = DateTime.UtcNow;
var expiresAt = authTime.AddDays(7);
var token = new JwtSecurityToken(
issuer: "lilibuy.com",
audience: "lilibuy.com",
claims: claims,
expires: expiresAt,
signingCredentials: creds);
return Ok(new
{
access_token = new JwtSecurityTokenHandler().WriteToken(token),
token_type = "Bearer",
profile = new
{
name = request.UserName,
auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
}
});
}
}
return BadRequest("Could not verify username and password.Pls check your information.");
}
}
}
再新建个model类
namespace asd.Controllers
{
public class TokenRequest
{
public string UserName {get;set; }
public string Password {get;set; }
}
}
先请求这个OauthController接口 获取到token之后 在客户端请求别的接口时加上开头的那个
Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoic21pbGVzYjEwMSIsImV4cCI6MTU1NjExMDc4MywiaXNzIjoibGlsaWJ1eS5jb20iLCJhdWQiOiJsaWxpYnV5LmNvbSJ9.xpvaxAwjubXRMd9auDQCfpvvslNbjY3q2n8zBI0aaQw
这里 Bearer+空格是一个固定的写法,使用的就是 Bearer 认证 所以这里是 Bearer
2019年04月18日21:43:54