栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.Net5 WebApi 使用过滤器实现token认证

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.Net5 WebApi 使用过滤器实现token认证

1.添加过滤器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Demo_Api1.Service
{
    public class UsersAtuhorizeAttribute : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var token = context.HttpContext.Request.Headers["token"]; //获取请求头header携带的token值
            if (token != "12313") //进行比较
            {
                //不通过,则返回验证失败
                context.Result = new JsonResult(
                    new
                    {
                        code = -1,
                        msg = "验证失败"
                    }); 
            }
        }
    }
}

2.使用filter实现验证

使用 TypeFilter 标记Controller或者方法 

[TypeFilter(typeof(UsersAtuhorizeAttribute))]

  也可以用ServiceFilter(定义多种生命周期过滤器)

        先在configservices注册

然后使用 [ServiceFilter(typeof(UsersAtuhorizeAttribute))] 标记controller或者方法

 

使用网页请求访问



	
		
		测试
		
		
	
	
		
			
			
			
		
		
	

 点按钮请求用户,断点调试可以进入过滤器,并获取到这次携带的token:123123,认证通过!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/911175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号