• 新增配置文件

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

.net core 学习小结之 JWT 认证授权的更多相关文章

  1. 【ASP.NET Core学习】使用JWT认证授权

    概述 认证授权是很多系统的基本功能 , 在以前PC的时代 , 通常是基于cookies-session这样的方式实现认证授权 , 在那个时候通常系统的用户量都不会很大, 所以这种方式也一直很好运行, ...

  2. .net core 学习小结之 Cookie-based认证

    在startup中添加授权相关的管道 using System; using System.Collections.Generic; using System.Linq; using System.T ...

  3. Dotnet core使用JWT认证授权最佳实践(二)

    最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 第一部分:Dotnet core使用JWT认证授权最佳实践(一) ...

  4. 任务35:JWT 认证授权介绍

    任务35:JWT 认证授权介绍 应用场景主要是移动端或者PC端前后分离的场景 直接对客户端API的请求 例如访问admin/Index 没有权限返回403. 需要客户端手动的再发动请求,这是一个拿to ...

  5. .net core gRPC与IdentityServer4集成认证授权

    前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...

  6. Dotnet core使用JWT认证授权最佳实践(一)

    最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 一.JWT JSON Web Token (JWT)是一个开放标准 ...

  7. 二手商城集成jwt认证授权

    ------------恢复内容开始------------ 使用jwt进行认证授权的主要流程 参考博客(https://www.cnblogs.com/RayWang/p/9536524.html) ...

  8. .net core 学习小结之 自定义JWT授权

    自定义token的验证类 using System; using System.Collections.Generic; using System.IO; using System.Linq; usi ...

  9. ASP.NET Core 3.1使用JWT认证Token授权 以及刷新Token

    传统Session所暴露的问题 Session: 用户每次在计算机身份认证之后,在服务器内存中会存放一个session,在客户端会保存一个cookie,以便在下次用户请求时进行身份核验.但是这样就暴露 ...

随机推荐

  1. SQL语句 数据类型

    6.1 Data Type 查看数据所占空间的两个函数: -- 查看所占字节数 select length('你好,世界') from dual; -- 查看所占字符数,即多少个字母,多少个汉字 se ...

  2. POJ-2104-Kth Number(主席树)

    链接: https://vjudge.net/problem/POJ-2104#author=malic 题意: 给定一个数组 a[1...n],数组元素各不相同,你的程序要对每次查询Q(i,j,k) ...

  3. 【NOIP2016提高A组模拟10.15】最大化

    题目 分析 枚举两个纵坐标i.j,接着表示枚举区域的上下边界, 设对于每个横坐标区域的前缀和和为\(s_l\),枚举k, 显然当\(s_k>s_l\)时,以(i,k)为左上角,(j,k)为右下角 ...

  4. 【windows&flask】flask通过service自动运行

    最近在学习在windows平台用flask框架提供Restful API服务,需要使得flask的windows应用能够开机自动运行,并且后台运行,所以通过service来实现. 首先尝试的是在自己派 ...

  5. php使用ob缓存来实现动态页面静态化

    php7中的php.ini 默认开启 output_buffering = 4096 例子: <?phpinclude_once 'common/common.php';//数据库操作方法 $f ...

  6. 修改apache2配置,禁止目录访问+禁止访问.git文件夹

    通过url访问服务器,无论是本地服务器还是远程服务器 如果你的文件根目录里有 index.html,index.php,浏览器就会显示 index.html的内容,如果没有 index.html,浏览 ...

  7. StringBuffer的s1.capacity()是多少?

    定义有StringBuffer s1=new StringBuffer(10);s1.append(“1234”)则s1.length()和s1.capacity()分别是多少? StringBuff ...

  8. jQuery file upload cropper的 click .preview事件没有绑定成功

    测试 修改https://github.com/tkvw/jQuery-File-Upload/blob/master/basic-plus.html var node = $('<p id=& ...

  9. 测试版和正式版微信小程序共享存储空间问题

    一般习惯将变量存储在小程序的storage缓存中,然后用到的时候再去取.但是有一次我在做小程序相关内容的时候发现,对于苹果手机,测试版本小程序和正式版本小程序的缓存变量是相互通用的.

  10. IntelliJ IDEA2018破解教程

    破解方法:下载破解补丁→修改配置文件→输入激活码→激活成功 由于JetBrains封杀,大部分激活服务器已经不能使用,使用下面的比较麻烦的方法也可以进行破解,但是有效期是到2100年(emmmm,也算 ...