.Net Core 3.0 Api json web token 中间件签权验证和 CORS 中间件处理跨域请求

第一步:在Nuget上安装"Microsoft.AspNet.WebApi.Cors"包,并对api controller使用[EnableCors]特性以及Microsoft.AspNetCore.Authentication.JwtBearer包

第二步:创建.netcore API项目 /控制器:AuthenticateController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using static JSON_WEB_Token.Helper;

namespace JSON_WEB_Token.Controllers
{  //跨域标签
    [EnableCors("anyPolicy")]
    //API接口打上Authorize标签
    [Authorize]
    [ApiController]
    //路由配置
    [Route("api/[controller]/[action]")]
    public class AuthenticateController : ControllerBase
    {
        private JwtSettingsModel _jwtSettings;
        public AuthenticateController(IOptions<JwtSettingsModel> jwtSetting)
        {
            _jwtSettings = jwtSetting.Value;
        }

        [HttpPost]
        public IActionResult Token([FromBody]PasswordModel request)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecetKey));

            string userId = request.UserName == null ? request.UserName : request.UserNo;
            if (request.UserName != "test" && request.PassWord != "123" )
            {
                return BadRequest();
            }

            var tokenModel = Helper.GetAccessTokenModel
            (new UserData()
            {
                UserGid = strUserGid,
                UserNo = "test"
            },
            24 * 365
            );

            return Ok(tokenModel);
        }

    }

    public class PasswordModel
    {
        public string UserName { get; set; }
        public string PassWord { get; set; }
        public string UserNo { get; set; }
        public string ClientSecret { get; set; }

    }
}

第三步: Helper

using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace JSON_WEB_Token
{
    public  class Helper
    {
        public  static AccessTokenResponse GetAccessTokenModel(UserData userData, int hours = 24, DateTime? expireTimeSpan = null)
        {
            JwtSettingsModel _jwtSettings = GetAppsettings<JwtSettingsModel>("JwtSettings");
            //创建claim
            var claim = new Claim[]{
                    new Claim(ClaimTypes.Sid,userData.UserGid.ToString()),
                    new Claim(ClaimTypes.Name,userData.UserNo),
                    new Claim(ClaimTypes.Role,TokenRoleType.UserApp),

                   };
            //对称秘钥 签名秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecetKey));
            //签名证书(秘钥,加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token
            DateTime expiresDate = expireTimeSpan ?? System.DateTime.Now.AddHours(hours);

            var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, expiresDate, creds);

            //保存token
            var accessTokenModel = new AccessTokenResponse();
            accessTokenModel.TokenType = "Bearer";
            accessTokenModel.UserNo = userData.UserNo;
            accessTokenModel.ExpiresDate = DateTimeToTimestamp(expiresDate);
            accessTokenModel.AccessToken = new JwtSecurityTokenHandler().WriteToken(token);
            return accessTokenModel;

        }

        public  static long DateTimeToTimestamp(DateTime dateTime)
        {
            var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
            return Convert.ToInt64((dateTime - start).TotalSeconds);
        }
        public class UserData
        {
            public Guid UserGid { get; set; }
            public string UserNo { get; set; }
            [Required]
            public string UserName { get; set; }
            public string PassWord { get; set; }

        }

        public class AccessTokenResponse
        {
            public string TokenType { get; set; } = "Bearer";
            public string UserNo { get; set; }
            public string AccessToken { get; set; }
            public long ExpiresDate { get; set; }
            public Guid ShopGid { get; set; }
            public string ShopName { get; set; }
            public Guid UserGid { get; set; }

        }
        /// <summary>
        /// 获取配置文件信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="setKey"></param>
        /// <returns></returns>
        public static T GetAppsettings<T>(string setKey)
        {

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json").Build();
            return builder.GetSection(setKey).Get<T>();
        }

        /// <summary>
        /// Token用户类型
        /// </summary>
        public class TokenRoleType
        {
            /// <summary>
            /// 匿名Token
            /// </summary>
            public const string GuoWaiApp = "国外渠道";

            /// <summary>
            /// 用户Token
            /// </summary>
            public const string UserApp = "国内渠道";

        }

    }

}

第四:JwtSettingsModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JSON_WEB_Token
{
    public class JwtSettingsModel
    {
        //token是谁颁发的
        public string Issuer { get; set; }
        //token可以给哪些客户端使用
        public string Audience { get; set; }
        //加密的key 必须是16个字符以上,要大于128个字节
        public string SecetKey { get; set; }
    }

    public class AccessTokenErrModel
    {
        public string AppId { get; set; }

        public string errcode { get; set; }
        public string errmsg { get; set; }

        public Guid UserGid { get; set; }

    }
}

第五:appsettings

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "AllowedHosts": "*",

  "JwtSettings": {
    "Issuer": "http://localhost:44305",
    "Audience": "http://localhost:44305",
    "SecetKey": "HelloWorldHelloWorldHelloWorld"
  }
}

第六:Startup

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace JSON_WEB_Token
{
    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)
        {
            services.AddControllers();

            #region json  web   token  添加认证服务
            //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中
            services.Configure<JwtSettingsModel>(Configuration.GetSection("JwtSettings"));

            //使用Bind的方式读取配置
            //将配置绑定到JwtSettings实例中
            var jwtSettings = new JwtSettingsModel();
            Configuration.Bind("JwtSettings", jwtSettings);

            services.AddAuthentication(options => {
                //认证middleware配置
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options  =>
            {
                //options.SaveToken = true;
                //options.RequireHttpsMetadata = false;
                //主要是jwt  token参数设置
                options.TokenValidationParameters = new TokenValidationParameters
                {

                    //Token颁发机构
                    ValidIssuer = jwtSettings.Issuer,
                    //颁发给谁
                    ValidAudience = jwtSettings.Audience,
                    //这里的key要进行加密
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecetKey))

                };
            });
            #endregion

            #region 注册跨域请求服务 CORS 中间件处理跨域请求
            //注册跨域请求服务 允许所有来源、所有方法、所有请求标头、允许请求凭据
            services.AddCors(options =>
                    {
                        //注册默认策略
                        options.AddDefaultPolicy( builder =>
                        {
                            builder.AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            // .AllowCredentials()
                            ;
                        });
                        //注册一个策略名称
                        options.AddPolicy("anyPolicy", builder =>
                        {
                        builder.WithOrigins("http://127.0.0.1:9102", "https://www.baidu.com")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        // .AllowCredentials()
                        ;
                        });
                    });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            #endregion
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseHttpsRedirection();
            /////////////////////////////////////////////
            //授权(Authorization)
            app.UseAuthorization();
            ///添加中间件(Middleware) 启用验证
            app.UseAuthentication();
            /////////////////////////////////////////////////
            app.UseCors("anyPolicy"); // 设置全局跨域
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller=Authenticate}/{action=Index}/{id?}");
            });
        }
    }
}

第七:postman请求

原文地址:https://www.cnblogs.com/Warmsunshine/p/11957904.html

时间: 2024-11-09 01:41:00

.Net Core 3.0 Api json web token 中间件签权验证和 CORS 中间件处理跨域请求的相关文章

Handle Refresh Token Using ASP.NET Core 2.0 And JSON Web Token

来源:   https://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/ In this article , you will learn how to deal with the refresh token when you use jwt (JSON Web Token) as your access_token. Backgroud Many peo

JSON Web Token (JWT) 实现与使用方法

1. JSON Web Token是什么 JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的.自包含的方式,用于作为JSON对象在各方之间安全地传输信息.该信息可以被验证和信任,因为它是数字签名的. 2. 什么时候你应该用JSON Web Tokens 下列场景中使用JSON Web Token是很有用的: Authorization (授权) : 这是使用JWT的最常见场景.一旦用户登录,后续每个请求都将包含JWT,允许用户访问该令牌允许的路由.服务

jquery跨域请求json数据

//服务端生成json数据json.php <?php $json=array("Volvo","BMW","SAAB"); $cb = $_GET['callback']; echo $cb.'('.json_encode($json, true).')'; ?> //客户端Ajax请求数据<script> $(document).ready(function() { var url="http://域名/js

JSON Web Token in ASP.NET Web API 2 using Owin

In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separate the Authorization Server and the Resource Server by unifying the "decryptionKey" and "validationKey" key values in machineKey node

使用json web token

由来 做了这么长时间的web开发,从JAVA EE中的jsf,spring,hibernate框架,到spring web MVC,到用php框架thinkPHP,到现在的nodejs,我自己的看法是越来越喜欢干净整洁的web层,之前用jsf开发做view层的时候,用的primefaces做的界面显示,虽然primefaces的确提供了很大的便利,可以让开发人员专注于业务逻辑开发,这样其实就省去了前端开发的工作.而后来发现有些客户需要的展现形式很难实现,或者通过拼凑的方法实现的结果效率不高.使用

json web token 网上学习笔记

JSON Web Token(JWT) - 实现系统集成授权访问 这是一个第三方系统访问AnyReport报表系统使用JWT授权的实现案例,AnyReport报表系统暴露报表资源URL供第三方系统访问,第三方系统可以使用iframe,src设置为报表链接访问报表资源,这时资源URL类似restful api需要被认证的系统才能访问,通过JWT的好处是不需要做登录认证在服务器端建立session. JWT组成部分 JSON web Token 简称JWT,是一种token的URL安全方法,用于在网

理解JWT(JSON Web Token)认证

最近想做个小程序,需要用到授权认证流程.以前项目都是用的 OAuth2 认证,但是Sanic 使用OAuth2 不太方便,就想试一下 JWT 的认证方式.这一篇主要内容是 JWT 的认证原理,以及python 使用 jwt 认识的实践. 几种常用的认证机制 HTTP Basic Auth HTTP Basic Auth 在HTTP中,基本认证是一种用来允许Web浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式,通常用户名和明码会通过HTTP头传递. 在发送之前是以用

[认证授权] 2.OAuth2授权(续) &amp; JWT(JSON Web Token)

1 RFC6749还有哪些可以完善的? 1.1 撤销Token 在上篇[认证授权] 1.OAuth2授权中介绍到了OAuth2可以帮我们解决第三方Client访问受保护资源的问题,但是只提供了如何获得access_token,并未说明怎么来撤销一个access_token.关于这部分OAuth2单独定义了一个RFC7009 - OAuth 2.0 Token Revocation来解决撤销Token问题. 1.2 Token对Client的不透明问题 OAuth2提供的“access_token

Json Web Token JJWT

什么是JWT? Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景.JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密. jwt的组成 Header: 标题包含了令牌的元数据,并且在最小包含签名和