asp.net core web页面验证

简介:
本例是用简单角色验证方式来通过用户登录后,获取用户角色,每种角色可以通过[Authorize(Roles = "admin,user")]在Action上来控制访问的权限,也就是说,只有属性这个角色才能访问这个Action。

道先添加Microsoft.AspNetCore.Authentication.Cookies引用

在StartUp.cs的Configure方法中添加
1
2
3
4
5
6
7
8
9
10
11
12
13
//为验证添加中间件
app.UseCookieAuthentication( new  CookieAuthenticationOptions
{
     //验证方案名称
     AuthenticationScheme =  "loginvalidate" ,
     //没有权限时导航的登录action
     LoginPath =  new  Microsoft.AspNetCore.Http.PathString( "/login" ),
     //访问被拒绝后的acion
     AccessDeniedPath =  new  Microsoft.AspNetCore.Http.PathString( "/Home/NoPermission" ),      
     AutomaticAuthenticate =  true ,
     AutomaticChallenge =  true ,
     SlidingExpiration =  true
});


 

HomeController中的登录的action实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using  System.Collections.Generic;
using  System.Linq;
using  Microsoft.AspNetCore.Mvc;
using  Microsoft.AspNetCore.Authorization;
using  System.Security.Claims;
  
namespace  webAuth.Controllers
{
     /// <summary>
     /// 本Controller允许admin和user两种角色可以访问
     /// </summary>
     [Authorize(Roles =  "admin,user" )]
     public  class  HomeController : Controller
     {
         public  IActionResult Index()
         {
             return  View();
         }
         /// <summary>
         /// aobout只允许user角色访问
         /// </summary>
         /// <returns></returns>
         [Authorize(Roles =  "user" )]
         public  IActionResult About()
         {
             var  id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value;
             ViewData[ "Message" ] =  "UserID:" + id;
  
             return  View();
         }
         /// <summary>
         /// contact只允许admin角色访问
         /// </summary>
         /// <returns></returns>
         [Authorize(Roles =  "admin" )]
         public  IActionResult Contact()
         {
             var  id=User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value;
             ViewData[ "Message" ] =  "UserID:" + id;
  
             return  View();
         }
  
         public  IActionResult NoPermission()
         {
             return  View();
         }
  
         /// <summary>
         /// 允许所有登录者
         /// </summary>
         /// <param name="returnUrl">如果用户访问的不是登录页,returnUrl将把这个url传进来,待登录成功后返回这个地址</param>
         /// <returns></returns>
         [AllowAnonymous]
         [HttpGet( "login" )]
         public  IActionResult Login( string  returnUrl)
         {
             //判断是否验证
             if  (!HttpContext.User.Identity.IsAuthenticated)
             {
                 //把返回地址保存在前台的hide表单中
                 ViewBag.returnUrl = returnUrl;
             }
             ViewBag.error =  null ;
             return  View();
         }
         /// <summary>
         /// 允许所有登录者
         /// </summary>
         /// <param name="username">用户名</param>
         /// <param name="password">密码</param>
         /// <param name="returnUrl">返回u</param>
         /// <returns></returns>
         [AllowAnonymous]
         [HttpPost( "login" )]
         public  IActionResult Login( string  username,  string  password,  string  returnUrl)
         {
             //从数据库验证用户,关取出用户所需要信息
             var  users =  new  List<dynamic>() {
                 new  { ID = 1, UserName =  "zsf" ,Password= "111" , Name =  "张三丰" , RoleTypeID = 1, RoleType =  "admin" , RoleTypeName =  "管理员"  },
                  new  { ID = 2, UserName =  "zwj" ,Password= "222" , Name =  "张无忌" , RoleTypeID = 2, RoleType =  "user" , RoleTypeName =  "普通用户"  }
             };
             var  user = users.SingleOrDefault(u => u.UserName == username && u.Password == password);
             if  (user!= null )
             {
                 //登录成功后,设置声明
                 var  claims =  new  Claim[] {
                       new  Claim(ClaimTypes.UserData,username),
                       new  Claim(ClaimTypes.Role,user.RoleType),
                       new  Claim(ClaimTypes.Name,user.Name),
                       new  Claim(ClaimTypes.Sid,user.ID.ToString())
                 };
                 HttpContext.Authentication.SignInAsync( "loginvalidate" new  ClaimsPrincipal( new  ClaimsIdentity(claims,  "Cookie" )));
                 HttpContext.User =  new  ClaimsPrincipal( new  ClaimsIdentity(claims));
                 return  new  RedirectResult(returnUrl ==  null  "/"  : returnUrl);
             }
             else
             {
                 ViewBag.error =  "用户名或密码错误!" ;
                 return  View();
             }
         }
     }
}


 

Login.cshtml页面如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@{
     Layout = null;
}
<!DOCTYPE html>
< html >
< head >
     < meta  charset = "utf-8"  />
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1.0"  />
     < title >登录</ title >
     < link  href = "~/lib/bootstrap/dist/css/bootstrap.css"  rel = "stylesheet"  />
     < style >
         .col-md-12 {
             text-align: center;
             margin-top: 10px;
         }
  
         .input-group {
             width: 300px;
             margin: 0 auto;
         }     
         .input-group-addon{
             width:80px;
        
     </ style >
</ head >
< body >
     < form  method = "post"  action = "/login" >
         < div  class = "container" >
             < div  class = "row"  style = "margin-top:200px" >
                 < div  class = "col-md-12" >
                     < div  class = "input-group" >
                         < span  class = "input-group-addon"  id = "basic-addon1" >用户名</ span >
                         < input  type = "text"  class = "form-control"  name = "username"  aria-describedby = "basic-addon1" >
                     </ div >
                 </ div >
             </ div >
             < div  class = "row" >
                 < div  class = "col-md-12" >
                     < div  class = "input-group" >
                         < span  class = "input-group-addon"  id = "basic-addon1" >密码</ span >
                         < input  type = "password"  class = "form-control"  name = "password"  aria-describedby = "basic-addon1" >
                     </ div >
                 </ div >
             </ div >
             < div  class = "row" >
                 < div  class = "col-md-12" >
                     < div  class = "input-group"  style = "text-align:right;" >
                         < input  type = "hidden"  value = "@ViewBag.returnUrl"  name = "returnUrl"  />
                         < button  type = "submit"  class = "btn btn-primary"  style = "width:90px" >登录</ button >
                     </ div >
                 </ div >
             </ div >
             @if (ViewBag.error != null)
             {
                 < font  color = "red" >@ViewBag.error</ font >
             }
         </ div >
     </ form >
     < script  src = "~/lib/bootstrap/dist/js/bootstrap.js" ></ script >
     < script  src = "~/lib/jquery/dist/jquery.js" ></ script >
</ body >
</ html >


如果在其他页面使用User,可以像下面这样使用

<span>当前用户:@User.Identity.Name</span>

当然也可以从User中查到其他登录时存储的Claim的值

 

登录成功后

wKiom1iN8sGC2_SMAATEwuHRSqo120.png-wh_50                            

登录成功后访问没有权限页面(当然可以不让这种角色看到不能访问的链接)

wKioL1iN8tnjfJHHAAJ_pkMpPRk495.png-wh_50
















本文转自桂素伟51CTO博客,原文链接:http://blog.51cto.com/axzxs/1894399 ,如需转载请自行联系原作者



相关文章
|
5月前
|
开发框架 .NET C#
ASP.NET Core Blazor 路由配置和导航
大家好,我是码农刚子。本文系统介绍Blazor单页应用的路由机制,涵盖基础配置、路由参数、编程式导航及高级功能。通过@page指令定义路由,支持参数约束、可选参数与通配符捕获,结合NavigationManager实现页面跳转与参数传递,并演示用户管理、产品展示等典型场景,全面掌握Blazor路由从入门到实战的完整方案。
475 6
|
开发框架 .NET 开发者
简化 ASP.NET Core 依赖注入(DI)注册-Scrutor
Scrutor 是一个简化 ASP.NET Core 应用程序中依赖注入(DI)注册过程的开源库,支持自动扫描和注册服务。通过简单的配置,开发者可以轻松地从指定程序集中筛选、注册服务,并设置其生命周期,同时支持服务装饰等高级功能。适用于大型项目,提高代码的可维护性和简洁性。仓库地址:&lt;https://github.com/khellang/Scrutor&gt;
403 5
|
11月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
535 35
|
运维 前端开发 C#
一套以用户体验出发的.NET8 Web开源框架
一套以用户体验出发的.NET8 Web开源框架
388 7
一套以用户体验出发的.NET8 Web开源框架
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
277 14
|
开发框架 算法 中间件
ASP.NET Core 中的速率限制中间件
在ASP.NET Core中,速率限制中间件用于控制客户端请求速率,防止服务器过载并提高安全性。通过`AddRateLimiter`注册服务,并配置不同策略如固定窗口、滑动窗口、令牌桶和并发限制。这些策略可在全局、控制器或动作级别应用,支持自定义响应处理。使用中间件`UseRateLimiter`启用限流功能,并可通过属性禁用特定控制器或动作的限流。这有助于有效保护API免受滥用和过载。 欢迎关注我的公众号:Net分享 (239字符)
343 1
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
409 3
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
.NET 开发框架 JavaScript
|
JavaScript .NET 数据安全/隐私保护
ASP.NET中验证控件的使用
原文:ASP.NET中验证控件的使用 前言:     前几日,无奈用JS判断控件的有效性,发现的确是一件费力、费神的事情!特别是针对邮件格式、邮政编码等的关于正则表达式的JS验证(其中涉及正则表达式的比较等,较烦~)。
974 0