zoukankan      html  css  js  c++  java
  • 36-应用Jwtbearer Authentication

    新建.net core webapi项目

    E:coding
    etcore>dotnet new webapi --name JwtAuthSample

    创建需要用到的实体对象类

    namespace JwtAuthSample.Models
    {
        public class JwtSettings{
            //发现者
            public string Issure{get;set;}
            //使用者
            public string Audience{get;set;}
            //jwt使用的密码
            public string SecretKey {get;set;}
    
        }
    }

    在appsettings.json 中增加映射到实体类JwtSettings的配置文件

    "JwtSettings":{
        "Issure":"http://localhost:5000",
        "Audience":"http://localhost:5000",
        "SecretKey":"123456789@byd@33311fasdfsad"
      }

    在StartUp.cs方法ConfigureServices中配置如下代码,用于Jwt验证

      public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
                services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
                var jwtSetting =  new JwtSettings();
                Configuration.Bind("JwtSettings",jwtSetting);
    
                services.AddAuthentication(options=>{
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(jwtOption=>{
                    jwtOption.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                        ValidIssuer = jwtSetting.Issure,
                        ValidAudience = jwtSetting.Audience,
                        IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
                            System.Text.Encoding.UTF8.GetBytes(jwtSetting.SecretKey)
                        )
                    };
                });
            }

    为了让受权生效,需要在Configure启用授权

    接下来测试授权有没有生效

    需要在要授权的类或方法上加下[Authorize]特性

    通过测试器访问 http://localhost:5000/api/values/ ,会出出现401未授权错误

  • 相关阅读:
    页面滚动
    代码提交报错
    校区下部门 及校区下员工
    表查询
    Jemeter命令执行
    抓包工具
    彻底解决mac下terminal路径显示问题
    PHP 性能分析第二篇: Xhgui In-Depth
    PHP 性能分析第一篇: Intro to Xhprof & Xhgui
    phpredis pipeline
  • 原文地址:https://www.cnblogs.com/qinzb/p/9351774.html
Copyright © 2011-2022 走看看