首页 > 其他分享 >.Net Api + Vue前后端分离项目中的jwt令牌应用

.Net Api + Vue前后端分离项目中的jwt令牌应用

时间:2022-10-20 19:12:49浏览次数:46  
标签:Vue RegisterEntity app jwt RegisterUserPassword Api result new loginDto

1.Start up 里面配置JWT认证方案

       //认证方案
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(
                option =>
                {
                    option.TokenValidationParameters = new TokenValidationParameters
                    {
                        //是否验证发行人
                        ValidateIssuer = true,
                        ValidIssuer = Configuration["JwtConfig:Issuer"],//发行人

                        //是否验证受众人
                        ValidateAudience = true,
                        ValidAudience = Configuration["JwtConfig:Audience"],//受众人

                        //是否验证密钥
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtConfig:key"])),

                        ValidateLifetime = true, //验证生命周期

                        RequireExpirationTime = true, //过期时间

                        ClockSkew = TimeSpan.Zero   //平滑过期偏移时间
                    };
                }
            );

2.appsettings.json配置JWT

  "JwtConfig": {
    "key": "JWTStudyWebsite_DI20DXU3",
    "Issuer": "mahang",
    "Audience": "wlw"
  }

3. 生成令牌, 示例:登录成功生成令牌

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="RegisterEntity"></param>
        /// <param name="RegisterUserPassword"></param>
        /// <returns></returns>
        public ResultDto Login(LoginDto loginDto)
        {
            ResultDto result = new ResultDto();

            var registerName = registerRepository.Query(x => (x.RegisterUserName == loginDto.RegisterEntity || x.RegisterUserEmail == loginDto.RegisterEntity || x.RegisterUserPhone == loginDto.RegisterEntity)).FirstOrDefault();

            var registerPassWord = registerRepository.Query(x => x.RegisterUserPassword == MD5HashUtility.MD5Hash(loginDto.RegisterUserPassword));

            if (registerName == null && registerPassWord.Count() == 0)
            {
                result.Message = "未注册,请先注册!";
                return result;
            }
            else
            {
                if (registerName == null)
                {
                    result.Message = "用户名输入错误,请重新输入!";
                    return result;
                }
                else
                {
                    if (MD5HashUtility.MD5Hash(loginDto.RegisterUserPassword) != registerName.RegisterUserPassword)
                    {
                        result.Message = "密码输入错误,请重新输入!";
                        return result;
                    }
                    else
                    {
                        //写Session或Cookies换成JWT
                        IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,registerName.RegisterUserName),
                        new Claim(JwtClaimTypes.Name,registerName.RegisterUserPassword)
                    };

                        //JWT密钥
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"]));

                        //算法
                        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        //过期时间
                        DateTime expires = DateTime.UtcNow.AddHours(10);


                        //Payload负载
                        var token = new JwtSecurityToken(
                            issuer: configuration["JwtConfig:Issuer"],
                            audience: configuration["JwtConfig:Audience"],
                            claims: claims,
                            notBefore: DateTime.UtcNow,
                            expires: expires,
                            signingCredentials: cred
                            );

                        var handler = new JwtSecurityTokenHandler();

                        //生成令牌
                        string jwt = handler.WriteToken(token);
                        result.Code = 200;
                        result.Message = "登录成功!";
                        result.Success = new LoginDto
                        {
                            RegisterEntity = loginDto.RegisterEntity,
                            RegisterUserPassword = loginDto.RegisterUserPassword,
                            Token = jwt
                        };
                    }
                }
            }
            return result;
        }
    }

  4.Start up 在AddSwaggerGen中配置小锁

services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "InterviewSystem.WebApi", Version = "v1" });
                //xml显示swgger注释
                options.IncludeXmlComments(System.IO.Directory.GetCurrentDirectory() + @"\\bin\\Debug\\net5.0\\InterviewSystem.WebApi.xml");

                //开启权限小锁
                options.OperationFilter<AddResponseHeadersFilter>();
                options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                options.OperationFilter<SecurityRequirementsOperationFilter>();

                //在header中添加token,传递到后台
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });
            });

5.配置相应的认证中间件和授权中间件

 // 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();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "InterviewSystem.WebApi v1"));
            }

            //启用静态文件浏览功能
            app.UseStaticFiles();

            //Https中间件
            app.UseHttpsRedirection();

            // 跨域
            app.UseCors();

            //路由中间件
            app.UseRouting();

            //认证中间件
            app.UseAuthentication();

            //授权中间件
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

5.在控制器中添加全局特性

 

 6.在Vue中,登录成功后用localStorage存储Token

//登录
submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { axios .post("Login/Login", this.ruleForm) .then((res) => { if (res.data.Code != 200) { this.$message.error(res.data.Message); } else { this.$message({ message: res.data.Message, type: "success", }); sessionStorage.setItem("RegisterEntity",this.ruleForm.RegisterEntity); localStorage.setItem("Token",res.data.Success.Token) this.$router.push("/main/IntroductionVue"); } }); } else { console.log("error submit!!"); return false; } }); },

7.Vue配置js文件,全局使用Token

import axios from "axios"

axios.defaults.baseURL = "https://localhost:44386/api/";

axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("Token")}`;

export default axios

 

标签:Vue,RegisterEntity,app,jwt,RegisterUserPassword,Api,result,new,loginDto
From: https://www.cnblogs.com/LaoMa0109/p/16810931.html

相关文章

  • .Net Core WebApi 控制器自动创建文件夹上传图片
    ///<summary>///异步图片或文件上传///</summary>///<paramname="formFile"></param>///<returns></returns>[Http......
  • Vue3.x+element-plus+ts踩坑笔记
    闲聊前段时间小颖在B站找了个学习vue3+TS的视频,自己尝试着搭建了一些基础代码,在实现功能的过程中遇到了一些问题,为了防止自己遗忘,写个随笔记录一下嘻嘻项目代码git地址:......
  • vue.config.js 常用的属性
    //vue.config.js文件是脚手架的配置文件const{defineConfig}=require("@vue/cli-service");module.exports=defineConfig({transpileDependencies:true,......
  • html项目引入element-ui和vue【转载】
    本地引用element-ui和vue<linkrel="stylesheet"type="text/css"href="./element.css"><scriptsrc="./js/vue.js"></script><scriptsrc="./js/element.js"></scrip......
  • Vue中点击空白区域让某个div消失
    需求:有个下拉框,下拉框选择自定义时,有个树状列表选择,再点击空白区域,树消失选择自定义会有个树  然后就是点击空白区域让树消失 <divclass="page"@click="clic......
  • vue使用WebUploader做大文件的分块和断点续传
    ​ 这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数下面直接贴代码吧,一些难懂的我大部分都加上......
  • 一种简单的视图层数据查询模块数据流--视图、路由、API
    背景简介实现前台项目的搜索页时,通常会将查询参数直接传给路由并显示在顶部的地址。params参数可以路径的一部分,因此可以理解;不过保留query的目的暂不清楚,对SSR模......
  • 前端Vue2-Day54
    ToDoList案例:组件间通信:父组件给子组件传参:父组件绑定值至子标签,子组件利用props接收。子组件给父组件传参:父组件绑定函数至子标签,子组件props接收函数,并设置methods进......
  • vue3:vue+nginx+php进行服务端部署的配置(nginx/1.18.0 / [email protected])
    一,开发环境中的配置:1,前端:vue的vue.config.jsconst{defineConfig}=require('@vue/cli-service')module.exports=defineConfig({transpileDependencies:t......
  • vue项目中给路由添加缓存配置
    <template><divid="app"><keep-alive:include="include"><router-viewv-if="$route.meta.keepAlive"/></keep-alive><router-viewv-if="!$......