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 引用传递和值传递
    jenkins 自动化部署 spring boot 项目(多图)
    Mybatis学习笔记,持续更新
    ubuntu 安装并远程连接redis
    ubuntu redis 集群安装,超简单多图细腻操作
    ubuntu16.04 的 使用笔记
    阿里云 ubuntu16.04 下 ftp 的快速应用(包罗疑难问题解决方案)
    k8s的#容器镜像
    kubectl命令出现【The connection to the server localhost:8080 was refused
    CIDR无类别域间路由
  • 原文地址:https://www.cnblogs.com/qinzb/p/9351774.html
Copyright © 2011-2022 走看看