首页 > 其他分享 >.net core 手写一个url的鉴权

.net core 手写一个url的鉴权

时间:2024-08-20 16:50:43浏览次数:4  
标签:core Task return AuthenticationScheme url public new 鉴权

思路::在startup.cs的configservice中配置自定义鉴权方式,在界面使用该方式

本章节实现一个简单的自定义鉴权:要求每个url后面要有参数UrlToken并且值为liping-123456,才可以访问成功,否则失败

 

1:配置一个自定义鉴权的文件

 1  public class CustomerAuthenticationConfig
 2  {
 3      public static void ConfigureServices(IServiceCollection services)
 4      {
 5 
 6          ////手写一个鉴权
 7          services.AddAuthentication(options =>
 8          {
 9              options.AddScheme<UrlTokenAuthenticationHandler>(
10                  UrlTokenAuthenticationDefaults.AuthenticationScheme,
11                  "ss");
12 
13              options.DefaultAuthenticateScheme = UrlTokenAuthenticationDefaults.AuthenticationScheme;
14              options.DefaultForbidScheme = UrlTokenAuthenticationDefaults.AuthenticationScheme;
15              options.DefaultChallengeScheme = UrlTokenAuthenticationDefaults.AuthenticationScheme;
16              options.DefaultSignInScheme = UrlTokenAuthenticationDefaults.AuthenticationScheme;
17              options.DefaultSignOutScheme = UrlTokenAuthenticationDefaults.AuthenticationScheme;
18          });
19 
20      }
21 
22      public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
23      {
24 
25          app.UseAuthentication();
26      }
27  }

 

2:具体如何实现鉴权的

 1  public class UrlTokenAuthenticationHandler : IAuthenticationHandler
 2  {
 3      private HttpContext context = null;
 4      private AuthenticationScheme scheme = null;
 5 
 6      /// <summary>
 7      /// 初始化
 8      /// </summary>
 9      /// <param name="scheme"></param>
10      /// <param name="context"></param>
11      /// <returns></returns>
12      public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
13      {
14          this.context = context;
15          this.scheme = scheme;
16          return Task.CompletedTask;
17      }
18      /// <summary>
19      /// 异步鉴权
20      /// 
21      /// </summary>
22      /// <returns></returns>
23      public Task<AuthenticateResult> AuthenticateAsync()
24      {
25          var urlInfo = context.Request.Query["UrlToken"];
26 
27          if (string.IsNullOrEmpty(urlInfo))
28          {
29 
30              return Task.FromResult(AuthenticateResult.NoResult());
31          }
32          else if ("liping-123456".Equals(urlInfo))
33          {
34 
35              var identity = new ClaimsIdentity();
36              identity.AddClaim(new Claim(ClaimTypes.Name, "liping"));
37              identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
38              identity.AddClaim(new Claim(ClaimTypes.Email, "[email protected]"));
39              identity.AddClaim(new Claim(ClaimTypes.Country, "China"));
40 
41 
42              ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal();
43              claimsPrincipal.AddIdentity(identity);
44 
45              return Task.FromResult(
46                  AuthenticateResult.Success(
47                      new AuthenticationTicket(claimsPrincipal, null, this.scheme.Name)
48                  ));
49          }
50          else
51          {
52              return Task.FromResult(AuthenticateResult.Fail("没有urltoken"));
53 
54          }
55 
56      }
57 
58      /// <summary>
59      /// 未登录
60      /// </summary>
61      /// <param name="properties"></param>
62      /// <returns></returns>
63      /// <exception cref="System.NotImplementedException"></exception>
64      public Task ChallengeAsync(AuthenticationProperties properties)
65      {
66          this.context.Response.Redirect("/Auth/noLogin");
67          return Task.CompletedTask;
68      }
69 
70      /// <summary>
71      /// 无权限
72      /// </summary>
73      /// <param name="properties"></param>
74      /// <returns></returns>
75      /// <exception cref="System.NotImplementedException"></exception>
76      public Task ForbidAsync(AuthenticationProperties properties)
77      {
78          this.context.Response.StatusCode = 403;
79          return Task.CompletedTask;
80      }
81 
82  }
83 
84  public static class UrlTokenAuthenticationDefaults
85  {
86 
87      public const string AuthenticationScheme = "LipingUrlTokenScheme";
88 
89  }

 

3:调用

 1 public class AuthController : Controller
 2 {
 3 
 4 
 5         /// <summary>
 6         /// 使用url方式存储用户信息
 7         /// https://localhost:44397/Auth/urltoken?UrlToken=liping-123456
 8         /// https://localhost:44397/Auth/urltoken
 9         /// </summary>
10         /// <returns></returns>
11         public async Task<IActionResult> UrlToken()
12         {
13 
14             var user = base.HttpContext.User;
15 
16             //startup方法中开放自己手写的鉴权方法
17             //通过https://localhost:44397/Auth/urltoken?UrlToken=liping-123456
18             //可以拿到登录信息
19             var result = await base.HttpContext.AuthenticateAsync(UrlTokenAuthenticationDefaults.AuthenticationScheme);
20 
21          
22             if (result?.Principal == null)
23             {
24                 return new JsonResult(new
25                 {
26                     Status = true,
27                     MSg = "认证失败"
28                 });
29             }
30             else
31             {
32                 List<string> infoList = new List<string>();
33                 foreach (var c in base.HttpContext.User.Identities.FirstOrDefault().Claims)
34                 {
35                     infoList.Add(c.Value);
36 
37                 }
38                 var data = Newtonsoft.Json.JsonConvert.SerializeObject(infoList);
39 
40                 return new JsonResult(new
41                 {
42                     Status = true,
43                     MSg = "成功",
44                     Data = data
45 
46                 });
47             }
48 
49         }
50 
51 
52 
53         public IActionResult NoLogin()
54         {
55             return View();
56         }
57 }

 

标签:core,Task,return,AuthenticationScheme,url,public,new,鉴权
From: https://www.cnblogs.com/hanliping/p/18369758

相关文章

  • .net core cookie 鉴权
    思路:在startup中的configservice设置cookie鉴权,在config方法中use鉴权,然后添加两个页面,一个登录页面,一个用户信息页面(登陆后才能访问,没有登录则返回失败或者需要登录) 1:添加一个cookie鉴权的方法1publicclassCookieAuthConfig2{3publicstaticvoidConfigureSe......
  • 短URL服务设计
    引言在营销系统里,为了增加系统的活跃用户数,经常会有各种各样的营销活动。这类活动几乎都是为了充分利用存量用户的价值,促使他们分享产品或App以达到触达到更多用户的目的。又或者是出于营销目的,群发优惠券触达短信这种场景。分享App活动页(或其他各种页面)时URL一般会带有各种参数......
  • k8s 手动更新 seldon core ca证书
    前言seldoncore报错:x509:certificatehasexpiredorisnotyetvalid:currenttime这是因为seldoncore默认的证书有效期为一年,需要helm重新安装才行,或者在安装seldoncore时启用了certManager自动更新证书helminstallseldon-coreseldon-core-operator--namespac......
  • springboot Failed to configure a DataSource: 'url' attribute is not specified
     问题,项目启动报错:Description:FailedtoconfigureaDataSource:'url'attributeisnotspecifiedandnoembeddeddatasourcecouldbeconfigured.Reason:FailedtodetermineasuitabledriverclassAction:Considerthefollowing:Ifyouwanta......
  • JS、C#中URL编码解码问题
    原文链接:https://www.sohu.com/a/468486142_120537920JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent。escapeeacape是BOM(浏览器对象模型(BrowserObjectModel))中的方法,只能对ASCII符号正确编码,而encodeURI、encodeURIComponent可以对所有的Unicode符号编码......
  • net core web api 支持xml参数 设置
    废话不多说,上教程。......
  • 使用EFCore连接达梦数据库
    为了快速验证EFCore连接达梦数据库,执行简单的查询语句,以下通过控制台程序来测试。这里的Demo项目,是比较早之前新建的,框架版本是.net6.0。1、项目添加EFCore和DM数据库的nuget包,添加成功之后查看项目文件的包引用(这里用到的是和6.0匹配的版本,其他版本相应升级依赖包即可)<Packa......
  • ThreadCore学习
    1.线程中的异常处理一般线程里面不允许出现异常,需要自己处理好,最好在线程里加个trycatch,#region异常处理//线程里面的异常是被吞掉了,因为已经脱离了try的范围了,WaitAll抓到多线程里面全部的异常//线程里面不允许出现......
  • Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64
    yuminstall报错:Cannotfindavalidbaseurlforrepo:centos-sclo-rh/x86_64问题原因CentOS7的SCL源在2024年6月30日停止维护了。当scl源里面默认使用了centos官方的地址,无法连接,需要替换为阿里云。解决办法1、重命名原来的文件:cd/etc/yum.repos.d/找到CentOS-SC......
  • 第1篇:aspnetcore,webapi项目打包发布,以.net7为例
    1.打包项目,打开visualstudio项目是ChenShiBao.AspNetCore7.0,发布成功并上传服务,启动服务以这个ChenShiBao.AspNetCore7.0.dll为准1.1生成发布包1.2选择发布形式2.在终端利用scp指令将本地已发布的应用传到linux服务上,【或通过第三方工具xshell上传发布包】终端命令:scp......