• 菜鸟入门【ASP.NET Core】10:Cookie-based认证实现


    准备工作

    新建MVC项目,然后用VSCode打开

    dotnet new mvc --name MvcCookieAuthSample

    在Controllers文件夹下新建AdminController.cs

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using MvcCookieAuthSample.Models;
    
    namespace MvcCookieAuthSample.Controllers
    {
        public class AdminController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }
        }
    }

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using MvcCookieAuthSample.Models;
    
    namespace MvcCookieAuthSample.Controllers
    {
        public class AdminController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }
        }
    }
    复制代码

    在Views文件夹下新建Admin文件夹,并在Admin文件夹下新建Index.cshtml

    @{
        ViewData["Title"] = "Admin";
    }
    <h2>@ViewData["Title"]</h2>
    
    <p>Admin Page</p>

    复制代码
    @{
        ViewData["Title"] = "Admin";
    }
    <h2>@ViewData["Title"]</h2>
    
    <p>Admin Page</p>
    复制代码

    运行结果:

    Cookie-based认证实现

    在AdminController中添加引用

    using Microsoft.AspNetCore.Authorization;

    然后可以给AdminController添加 [Authorize] 标签

     

    接下来需要把认证和授权引用进来,使用的是cookie的认证方式,所以在Startup.cs中添加认证的引用。

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;

    然后在Startup方法中进行cookie的依赖注入

                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options=>{//自定义登陆地址,不配置的话则默认为http://localhost:5000/Account/Login
                        options.LoginPath="/Account/MyLogin";
                    });

    然后要在Configure方法中把cookie中间件也添加进来,否则认证授权是不会生效的

    app.UseAuthentication();

    这时候再运行一下:

     

    发现已经自动跳转到登陆地址了。

     模拟登陆

     暂时不做登陆的,只是模拟一下登陆,首先创建一个AccountController.cs

    然后添加引用

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using System.Security.Claims;

    添加两个API用于登陆和登出

    复制代码
            //登陆
            public IActionResult MakeLogin()
            {
                var claims=new List<Claim>(){
                    new Claim(ClaimTypes.Name,"wangyuting"),
                    new Claim(ClaimTypes.Role,"admin")
    
                };
                //必须要加CookieAuthenticationDefaults.AuthenticationScheme,不然无法解析
                var claimsIdentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
    
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity));
                return Ok();
            }
    
            //登出
            public IActionResult Logout()
            {
                HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    
                return Ok();
            }
    复制代码

    访问http://localhost:5000/admin会

    跳转到http://localhost:5000/Account/MyLogin?ReturnUrl=%2Fadmin页面

    然后我们访问http://localhost:5000/Account/MakeLogin模拟登陆,

    然后再访问http://localhost:5000/admin

     

     最后访问http://localhost:5000/Account/logout登出,

    然后再访问http://localhost:5000/admin发现又跳转到我们自定义的登陆页面。

  • 相关阅读:
    Warning: Cannot modify header information
    curl_setopt(): CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
    PHP Warning: strtotime(): It is not safe to rely on the system's timezone settings.
    出现Deprecated: Function ereg_replace() is deprecated in 的原因及解决方法
    APMServ5.2.6 升级PHP版本 到高版本 5.3,5.4
    Apache无法启动解决 the requested operation has failed
    用json获取拉钩网的信息
    json
    如何用组件组装一个简单的机器人
    vue-组件
  • 原文地址:https://www.cnblogs.com/Agui520/p/8377033.html
Copyright © 2020-2023  润新知