.net core 学习小结之 JWT 认证授权
2024-08-29 20:21:18
- 新增配置文件
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"JwtSettings": {
"Issuer": "http://locahost:5000",
"Audience": "http://locahost:5000",
"SecretKey": "hello world this is my key for cyao"
}
}namespace JwtAuth
{
public class JwtSettings
{
///使用者
public string Issuer { get; set; }
///颁发者
public string Audience { get; set; }
///秘钥必须大于16个字符
public string SecretKey { get; set; }
}
} - 将配置文件读取映射到实体类,并且将jwt授权加入到管道中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace JwtAuth
{
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//将配置文件读取到settings
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
JwtSettings settings = new JwtSettings();
Configuration.Bind("JwtSettings", settings);
//添加授权信息
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
.AddJwtBearer(c => c.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters//添加jwt 授权信息
{
ValidIssuer = settings.Issuer,
ValidAudience = settings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey))
});
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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//向builder中添加授权的管道
app.UseAuthentication();
app.UseMvc();
}
}
} - 判断当前用户是否合法并且返回授权后的token信息
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace JwtAuth.Controllers
{
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
//添加dll的引用 Nuget Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IdentityModel.Tokens.Jwt;
[Route("Auth/[controller]")]
public class AuthController : Controller
{
public JwtSettings settings;
public AuthController(IOptions<JwtSettings> jwtsettings)
{
settings = jwtsettings.Value;
}
public IActionResult Token([FromBody]LoginInfo model)
{
if (ModelState.IsValid)
{
if (model.username == "cyao" && model.password == "")
{
//用户合法情况
//添加授权信息
var claims = new Claim[] { new Claim(ClaimTypes.Name, "cyao"), new Claim(ClaimTypes.Role, "admin") };
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
settings.Issuer,
settings.Audience,
claims,
DateTime.Now,
DateTime.Now.AddMinutes(),//过期时间
creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
}
return BadRequest();
}
}
public class LoginInfo
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}
}
最新文章
- Linux下VI命令详细介绍
- unity, Shader.Find的一个坑
- Mac中体验ASP.NET 5 beta2的K gen代码生成
- dba诊断之IO
- 在CentOS6.5上安装Tomcat7
- [原创]java WEB学习笔记70:Struts2 学习之路-- 输入验证,声明式验证,声明是验证原理
- HDU 5800 To My Girlfriend 背包
- javascript中ajax post实例详解
- IntelliJ IDEA 13怎么创建JAVA SE项目
- Poj 1166 The Clocks(bfs)
- 更改MYSQL数据库不区分大小写表名
- LeetCode - 185. Department Top Three Salaries
- ICC_lab总结——ICC_lab5:布线&;&;数字集成电路物理设计学习总结——布线
- html基础技巧:点击、placeholder、文本、字体、清楚浮动
- UVA 548 Tree 建树
- go语言基本语法
- 简单了解static
- Java并发之线程转储
- 【工具相关】web-HTML/CSS/JS Prettify的使用
- Leetcode 692 - Note