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未授权错误

  • 相关阅读:
    Vue2.1.7源码学习
    JavaScript 复制对象【Object.assign方法无法实现深复制】
    数组去重你知道几种?
    基于webpack2.x的vue2.x的多页面站点
    欲练JS,必先攻CSS——前端修行之路
    闭包的7种形式
    遇见未知的CSS
    redux 个人整理
    log4j.properties打印日志信息(1)
    Java Web开发之Servlet、JSP基础
  • 原文地址:https://www.cnblogs.com/qinzb/p/9351774.html
Copyright © 2011-2022 走看看