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

  • 相关阅读:
    java并发ThreadLocal
    PermGen space 与 Java heap space
    java vm内存设置
    linux下ssh使用和配置
    ubuntu进入命令登录界面
    7-21 求前缀表达式的值
    7-20 表达式转换
    7-19 求链式线性表的倒数第K项
    7-18 银行业务队列简单模拟
    7-17 汉诺塔的非递归实现
  • 原文地址:https://www.cnblogs.com/qinzb/p/9351774.html
Copyright © 2011-2022 走看看