博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asp.net core web页面验证
阅读量:7252 次
发布时间:2019-06-29

本文共 4349 字,大约阅读时间需要 14 分钟。

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

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

在StartUp.cs的Configure方法中添加
//为验证添加中间件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实现

using System.Collections.Generic;using System.Linq;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Authorization;using System.Security.Claims; namespace webAuth.Controllers{    ///     /// 本Controller允许admin和user两种角色可以访问    ///     [Authorize(Roles = "admin,user")]    public class HomeController : Controller    {        public IActionResult Index()        {            return View();        }        ///         /// aobout只允许user角色访问        ///         /// 
        [Authorize(Roles = "user")]        public IActionResult About()        {            var id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value;            ViewData["Message"] = "UserID:"+ id;             return View();        }        ///         /// contact只允许admin角色访问        ///         /// 
        [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();        }         ///         /// 允许所有登录者        ///         /// 
如果用户访问的不是登录页,returnUrl将把这个url传进来,待登录成功后返回这个地址        /// 
        [AllowAnonymous]        [HttpGet("login")]        public IActionResult Login(string returnUrl)        {            //判断是否验证            if (!HttpContext.User.Identity.IsAuthenticated)            {                //把返回地址保存在前台的hide表单中                ViewBag.returnUrl = returnUrl;            }            ViewBag.error = null;            return View();        }        /// 
        /// 允许所有登录者        ///         /// 
用户名        /// 
密码        /// 
返回u        /// 
        [AllowAnonymous]        [HttpPost("login")]        public IActionResult Login(string username, string password, string returnUrl)        {            //从数据库验证用户,关取出用户所需要信息            var users = new List
() {                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页面如下:

@{    Layout = null;}    
    
    登录    
        
        
            
                
                    
                        
用户名                        
                                                            
                
                    
                        
密码                        
                                                            
                
                    
                        
                        
登录                                                            @if (ViewBag.error != null)            {                
@ViewBag.error            }                
    

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

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

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

 

登录成功后

                            

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

转载地址:http://aiqbm.baihongyu.com/

你可能感兴趣的文章
Pyhton 第九章 正则表达式
查看>>
mysql主从配置
查看>>
Jconsole远程监控tomcat 的JVM内存(linux、windows)
查看>>
分布式项目(一)iot-pt
查看>>
JFreeChart开源图表组件在Java开发中的应用(一)
查看>>
使用ZooKeeper ACL特性进行znode控制
查看>>
struts2 跳转类型介绍 result type=chain、dispatcher、redirect(redirect-action)
查看>>
宜春之行
查看>>
我的友情链接
查看>>
Exchange2010 dag 的缷载
查看>>
2011/11/14 1:52 坚持就会胜利
查看>>
oracle概念和术语 建表时的一些参数pctfree initrans maxtrans sto
查看>>
我的友情链接
查看>>
转ApplicationContext的三种实现方式以及在web.xml配置的两种方式
查看>>
【我的软考之路】我的网工备考之路~
查看>>
mysql5.7.10安装
查看>>
IP数据包的分片与重组过程
查看>>
命好不如习惯好
查看>>
/etc/X11/xorg.conf 文件被误改后进不了图形化界面
查看>>
Android 通过反射及AIDL获取双卡手机SIM卡相关信息,及注册监听
查看>>