首页 > 其他分享 >全局授权注册

全局授权注册

时间:2023-07-30 09:03:32浏览次数:18  
标签:注册 await new context using var 授权 全局 Microsoft

  1 using System;
  2 using System.Security.Claims;
  3 using System.Security.Principal;
  4 using System.Threading.Tasks;
  5 using Microsoft.AspNetCore.Authentication;
  6 using Microsoft.AspNetCore.Authentication.Cookies;
  7 using Microsoft.AspNetCore.Authorization;
  8 using Microsoft.AspNetCore.Authorization.Infrastructure;
  9 using Microsoft.AspNetCore.Builder;
 10 using Microsoft.AspNetCore.Hosting;
 11 using Microsoft.AspNetCore.Http;
 12 using Microsoft.EntityFrameworkCore;
 13 using Microsoft.Extensions.DependencyInjection;
 14 using Microsoft.Extensions.Hosting;
 15 
 16 namespace ConsoleApp4
 17 {
 18     class Program
 19     {
 20         static void Main(string[] args)
 21         {
 22             Host.CreateDefaultBuilder()
 23                 .ConfigureWebHostDefaults(builder => builder
 24                     .ConfigureServices(collection => collection
 25                         .AddDbContext<UserDbContext>(options => options
 26                             .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AuthorizationDemo;Trusted_Connection=True;MultipleActiveResultSets=true")
 27                         )
 28                         .AddRouting()
 29                         .AddAuthorization(options => {                     //授权全局注册
 30                             var requirement = new RolesAuthorizationRequirement(new [] { "ADMIN" });            //角色授权要求对象
 31                             var policy = new AuthorizationPolicy(new IAuthorizationRequirement[] { requirement }, new string[0]);     //授权策略,第二个是授权方案名称
 32                             options.AddPolicy("HomePage", policy);     //随便起个名字
 33                         })
 34                         .AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie())
 35                     .Configure(app => app
 36                         .UseAuthentication()
 37                         .UseRouting()
 38                         .UseEndpoints(endpoints =>
 39                         {
 40                             endpoints.Map("/", RenderHomePageAsync);
 41                             endpoints.Map("Account/Login", SignInAsync);
 42                             endpoints.Map("Account/Logout", SignOutAsync);
 43                             endpoints.Map("Account/AccessDenied", DenyAccessAsync);
 44                         })))
 45                 .Build()
 46                 .Run();
 47         }
 48 
 49         public static async Task RenderHomePageAsync(HttpContext context)
 50         {
 51             if (context?.User?.Identity?.IsAuthenticated == true)
 52             {
 53                 var authorizationService = context.RequestServices.GetRequiredService<IAuthorizationService>();  //获取授权服务
 54                 var result = await authorizationService.AuthorizeAsync(context.User, "HomePage");                 //传递策略,在mvc中修改为特性
 55                 if (result.Succeeded)
 56                 {
 57                     await context.Response.WriteAsync(
 58                         @"<html>
 59                     <head><title>Index</title></head>
 60                     <body>" +
 61                         $"<h3>{context.User.Identity.Name}, you are authorized.</h3>" +
 62                         @"<a href='Account/Logout'>Sign Out</a>
 63                     </body>
 64                 </html>");
 65                 }
 66                 else
 67                 {
 68                     await context.ForbidAsync();
 69                 }
 70             }
 71             else
 72             {
 73                 await context.ChallengeAsync();
 74             }
 75         }
 76 
 77           public static async Task SignInAsync(HttpContext context)
 78         {
 79             if (string.Compare(context.Request.Method, "GET") == 0)
 80             {
 81                 await RenderLoginPageAsync(context, null, null, null);
 82             }
 83             else
 84             {
 85                 string userName = context.Request.Form["username"];
 86                 string password = context.Request.Form["password"];
 87                 var dbContext = context.RequestServices.GetRequiredService<UserDbContext>();
 88                 var user = await dbContext.Users.Include(it => it.Roles).SingleOrDefaultAsync(it => it.UserName == userName.ToUpper());
 89                 if (user?.Password == password)
 90                 {
 91                     var identity = new GenericIdentity(userName, CookieAuthenticationDefaults.AuthenticationScheme);
 92                     foreach (var role in user.Roles)
 93                     {
 94                         identity.AddClaim(new Claim(ClaimTypes.Role, role.NormalizedRoleName));
 95                     }
 96                     var principal = new ClaimsPrincipal(identity);
 97                     await context.SignInAsync(principal);
 98                 }
 99                 else
100                 {
101                     await RenderLoginPageAsync(context, userName, password, "Invalid user name or password!");
102                 }
103             }
104         }
105 
106         private static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage)
107         {
108             context.Response.ContentType = "text/html";
109             return context.Response.WriteAsync(
110                 @"<html>
111                 <head><title>Login</title></head>
112                 <body>
113                     <form method='post'>" +
114                             $"<input type='text' name='username' placeholder='User name' value = '{userName}' /> " +
115                             $"<input type='password' name='password' placeholder='Password' value = '{password}' /> " +
116                             @"<input type='submit' value='Sign In' />
117                     </form>" +
118                             $"<p style='color:red'>{errorMessage}</p>" +
119                     @"</body>
120             </html>");
121         }
122 
123         public static async Task SignOutAsync(HttpContext context)
124         {
125             await context.SignOutAsync();
126             await context.ChallengeAsync(new AuthenticationProperties { RedirectUri = "/" });
127         }
128 
129         public static Task DenyAccessAsync(HttpContext context)
130         {
131             return context.Response.WriteAsync(
132                 @"<html>
133                 <head><title>Index</title></head>
134                 <body>" +
135                 $"<h3>{context.User.Identity.Name}, your access is denied.</h3>" +
136                 @"<a href='/Account/Logout'>Sign Out</a>
137                 </body>
138             </html>");
139         } 
140 
141       
142     }
143 }

 

标签:注册,await,new,context,using,var,授权,全局,Microsoft
From: https://www.cnblogs.com/zzhpebg/p/17590954.html

相关文章

  • 全局注册授权策略
    1usingSystem;2usingSystem.Security.Claims;3usingSystem.Security.Principal;4usingSystem.Threading.Tasks;5usingMicrosoft.AspNetCore.Authentication;6usingMicrosoft.AspNetCore.Authentication.Cookies;7usingMicrosoft.AspNetCore......
  • Dubbo(五)_服务注册原理
    服务注册是指将服务暴露出来的过程,包括了服务解析、服务启动、服务注册三部分。其中服务解析就是将Dubbo的服务配置解析成Spring的Bean对象;服务启动是启动一个可以处理请求的服务;服务注册是指将服务信息保存到注册中心中,供服务消费方获取。Dubbo的注册中心支持Redis、Zooke......
  • Dubbo(四)_全局架构
    整体架构全局架构分为注册中心,通常为zk/redis;服务提供者Provider,用来提供并注册服务到注册中心;服务消费者Consumer,用来向注册中心订阅服务,当注册中心服务发生变动时notify通知消费者,消费者通过invoke远程调用服务提供者;Monitor监控者用来监控服务,统计服务的调用次数和调......
  • 6、Mysql创建用户以及授权
    文件夹就是数据库文件就是表数据行就是行 data下的mysql这个数据库里有张User表,里面保存了用户信息 showdatabases;查看所有数据库 usemysql;使用这个use数据库(进入这个文件夹) showtables;查看这个数据库下所有的表(文件)文件最后有个user,我们登陆mysql服务器......
  • 手写Nacos基本原理——服务注册 配置管理
    手写Nacos基本原理一、背景介绍二、思路方案三、过程nacosService代码pom文件配置文件具体类nacosSDK代码pom文件配置类具体类serviceA代码pom文件配置文件具体类serviceB代码pom文件配置文件具体类实现效果四、总结五、升华一、背景介绍之前在项目开发的过程中,对于Nacos的理解......
  • Python全局变量和局部变量
    目录1.python的全局变量和局部变量第一种:global定义全局变量在自定义函数内部第二种:全局定义全局变量,并给其赋值2.python类中public,protected,private定义方式3.python中类的实例化1.python的全局变量和局部变量全局变量定义:在函数外部定义的变量。所有函数内部都可以使用......
  • 基于C语言设计的全局光照明模型
    完整资料进入【数字空间】查看——搜索"writebug"Part1Whitted-StyleRayTracingStep0.算法流程为了渲染出一张图片,RayTrace()计算了给定像素点的色彩取值。根据光路可逆原理,可以从人眼作为出发点,沿着指向该pixel的某一点的方向发出一条ray。Step1:射线求交这条ray会碰到一个......
  • 多线程共享全局变量的问题
    线程之间共享全局变量多个线程都是在同一个进程中,多个线程使用的资源都是同一个进程中的资源,因此多线程间是共享全局变量问题示例1importthreading234#全局变量5g_num=0678#对g_num进行加操作9defsum_num1():10foriinrange(......
  • asp.net core 2.0 web api基于JWT自定义策略授权
    原文通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端验证通过即可能获取想要访问的资源。关于JWT的技术,可参考网络上文章,这里不作详细说明,这篇博文,主要说明在asp.netcore2.0中,基于jwt的webapi的权限设置,即在asp.netcore中怎么用JWT,再次......
  • Git常用命令(Git全局设置、获取Git仓库)
         ......