zoukankan      html  css  js  c++  java
  • 34-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();
            }
        }
    }

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

    @{
        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;

    然后在  public void ConfigureServices(IServiceCollection services)  方法中进行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发现又跳转到我们自定义的登陆页面。

  • 相关阅读:
    spark 集合交集差集运算
    Scala学习笔记1(安装)
    shell脚本调用spark-sql
    R语言中判断是否是整数。以及读写excel
    el-table的type="selection"的使用
    el-mement表单校验-校验失败时自动聚焦到失败的input框
    "org.eclipse.wst.validation" has been removed 导入maven 项目出错。
    java compiler level does not match the version of the installed java project facet 解决方案
    Referenced file contains errors (http://www.springframework.org/schema/context). For more information, right click on the message in the Problems
    编译异常 Caused by: java.lang.UnsupportedClassVersionError:
  • 原文地址:https://www.cnblogs.com/qinzb/p/9346642.html
Copyright © 2011-2022 走看看