• 新增配置文件

    {
    "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; }
    }
    }

最新文章

  1. Linux下VI命令详细介绍
  2. unity, Shader.Find的一个坑
  3. Mac中体验ASP.NET 5 beta2的K gen代码生成
  4. dba诊断之IO
  5. 在CentOS6.5上安装Tomcat7
  6. [原创]java WEB学习笔记70:Struts2 学习之路-- 输入验证,声明式验证,声明是验证原理
  7. HDU 5800 To My Girlfriend 背包
  8. javascript中ajax post实例详解
  9. IntelliJ IDEA 13怎么创建JAVA SE项目
  10. Poj 1166 The Clocks(bfs)
  11. 更改MYSQL数据库不区分大小写表名
  12. LeetCode - 185. Department Top Three Salaries
  13. ICC_lab总结——ICC_lab5:布线&amp;&amp;数字集成电路物理设计学习总结——布线
  14. html基础技巧:点击、placeholder、文本、字体、清楚浮动
  15. UVA 548 Tree 建树
  16. go语言基本语法
  17. 简单了解static
  18. Java并发之线程转储
  19. 【工具相关】web-HTML/CSS/JS Prettify的使用
  20. Leetcode 692 - Note

热门文章

  1. json格式字符串转字典
  2. 数据结构和算法(java版本)学习指南
  3. MyEclipse更改项目名web发布名字不改问题
  4. HTML5测试(二)
  5. 3D Computer Grapihcs Using OpenGL - 18 相机移动
  6. 8.Python标识符命名规范
  7. linux下挂载磁盘
  8. C:\WINDOWS\system32\drivers\etc\hosts文件的作用
  9. Group by的用法
  10. CentOS7 修改网卡名称为eth0 & 在VMWare中添加多网卡配置