• 新增配置文件

    {
    "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. Mybatis 动态sql(转载)

    原文地址:http://www.cnblogs.com/dongying/p/4092662.html 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个 ...

  2. ng-model 和ng-bind的区别

    也就是说 ng-model是绑定html输入的值-->到控制器的变量,输入值变了,控制器对应的变量message的值页变了,这样,在其他地方就可以使用这个变化后的值 ng-bind 是绑定控制器 ...

  3. 创建一个jFinal项目

    最近在做微信开发,于是用到了jfinal. 做一下解释: JFinal 是基于 Java 语言的极速 WEB + ORM 开发框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩 ...

  4. shell练习--关于关联数组自增统计判断的学习

    今天在书上看到了一个关联数组 let statarray["$ftype"]++  这样一个操作,用来做索引的自增统计,所以记下来 #!/bin/bash #统计文件类型 #关于关 ...

  5. net core 下 接受文件 测试

    /* IFormFileCollection Files 再Request对象下的From对象下的Files对象 public interface IFormFileCollection : IRea ...

  6. 用Java 实现断点续传 (HTTP)

    在web项目中上传文件夹现在已经成为了一个主流的需求.在OA,或者企业ERP系统中都有类似的需求.上传文件夹并且保留层级结构能够对用户行成很好的引导,用户使用起来也更方便.能够提供更高级的应用支撑. ...

  7. 联系人:ContactsContract类

    Android系统管理联系人的URI如下: ContactsContract.Contacts.CONTENT_URI                                     管理联系 ...

  8. linux crontab -e生成日期格式

    近期公司数据库服务器要上双活项目,实施顾问要收集服务器(磁盘性能数据)IO及VM的一些相关信息,并已日期时间格式生成文件 用crontab –e增加以下内容,它的作用是每隔1个小时启动一次iostat ...

  9. wannafly 练习赛11 B 假的字符串(字典树+建边找环)

    链接:https://www.nowcoder.com/acm/contest/59/B 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32768K,其他语言65536K 64bit ...

  10. android网络连接工具类

    该类的目的主要是判断设备的联网状态  检测设备是否连接了网络 package com.wotlab.home.moneyplantairs.utils; import android.content. ...