分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

.net core 2.0 登陆权限验证

发布时间:2023-09-06 01:08责任编辑:沈小雨关键词:暂无标签

首先在Startup的ConfigureServices方法添加一段权限代码

services.AddAuthentication(x=> { ???????????????x.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; ???????????????x.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; ???????????????x.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; ???????????}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x => ???????????????????{ ???????????????????????//登录地址 ???????????????????????x.LoginPath = "/Home/Login"; ???????????????????????//sid ???????????????????????x.Cookie.Name = "mycookie"; ???????????????????????x.Cookie.Path = "/"; ???????????????????????x.Cookie.HttpOnly = true; ???????????????????????x.Cookie.Expiration = new TimeSpan(0, 0, 30); ???????????????????????x.ExpireTimeSpan = new TimeSpan(0, 0, 30); ???????????????????});

这里整理下目录。

有个HomeController,首页的Index页面添加[Authorize],需要权限进入

有个Login的action,登录页

添加登录方法SignIn

public async Task<IActionResult> SignIn(LoginViewModel model) ???????{ ???????????if (ModelState.IsValid) ???????????{ ???????????????var claims = new List<Claim>(); ???????????????claims.Add(new Claim(ClaimTypes.Name, model.UserName)); ???????????????var identity = new ClaimsIdentity(claims, "login"); ???????????????var principal = new ClaimsPrincipal(identity); ???????????????await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); ???????????????if (principal.Identity.IsAuthenticated) ???????????????????return RedirectToAction("Index"); ???????????} ???????????return View(); ???????}

添加登录页面

@{ ???ViewData["Title"] = "Login";}<h2>Login</h2><form method="post" action="/home/SignIn"> ???用户名<input type="text" name="username" /> ???密码<input type="password" name="password" /> ???<button type="submit" class="btn">登录</button></form>

因为在Startup里面配置了当没权限时进入登录页面  

 ???????????????????????x.LoginPath = "/Home/Login";

此时运行程序,会跳转到登录页面

输入用户名密码登陆,登录验证成功后就可以跳转到Index了。

再添加个退出

public async Task<IActionResult> SignOut() ???????{ ???????????if (HttpContext.User.Identity.IsAuthenticated) ???????????????await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); ???????????return RedirectToAction("Login"); ???????} 

在页面上可以通过这段代码判断是否登录

Context.User.Identity.IsAuthenticated

.net core 2.0 登陆权限验证

原文地址:http://www.cnblogs.com/xiaoquangege/p/7472346.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved