.net 基于Cookie的身份认证

编程入门 行业动态 更新时间:2024-10-18 16:48:36

.net 基于Cookie的<a href=https://www.elefans.com/category/jswz/34/1737376.html style=身份认证"/>

.net 基于Cookie的身份认证

基于Cookie的身份认证

身份认证Authentication,用于认定用户是谁
鉴权Authorization,用于校验用户是否有访问某东西的权限

新建一个asp core web api项目

注册基于Cookie的身份认证服务

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{//重写身份认证失败的逻辑,默认是跳转到/Account/Login,这里改为直接返回401options.Events.OnRedirectToLogin = context =>{context.Response.StatusCode = StatusCodes.Status401Unauthorized;return Task.CompletedTask;};
});

使用身份认证中间件,这个中间件需要放在鉴权中间件之前(先身份认证后鉴权)

Controller的测试代码

使用[Authorize]特性表明该Controller下的所有Action需要进行鉴权
使用[AllowAnonymous]特性允许该Action匿名访问,就是不需要身份认证和鉴权就能访问,该特性一般是要给登录接口加(否则连登录接口都要鉴权的话人家怎么登录)

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;namespace AuthorizationTest.Controllers
{[ApiController][Route("[controller]/[action]")][Authorize]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet][AllowAnonymous]//允许匿名访问public object Login(){List<Claim> claims = new List<Claim>{//new Claim(ClaimTypes.Role, "Teacher") // Claim类似于一个键值对,用于存放信息,如性别:男};// ClaimsIdentity是Claim的集合,例如身份证,身份证含有很多信息// ClaimsPrincipal是实体,一个实体可以具有多个ClaimsIdentity,就好比一个人可以具有多个证ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));//登录HttpContext.SignInAsync(claimsPrincipal).Wait();//登录并指定身份认证策略,并配置过期时间//HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties//{//    ExpiresUtc = DateTime.UtcNow.AddMinutes(30), // 过期时间30分钟//}).Wait();return "登录成功";}[HttpGet]public IEnumerable<WeatherForecast> Get(){var rng = new Random();return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateTime.Now.AddDays(index),TemperatureC = rng.Next(-20, 55),Summary = Summaries[rng.Next(Summaries.Length)]}).ToArray();}}
}

启动项目,访问/WeatherForecast/Get发现报401,身份认证失败,因为没有登录,按F12打开浏览器调试工具,找到应用程序菜单,查看Cookie,此时是没有身份认证信息的

访问/WeatherForecast/Login返回登录成功
登录后查看Cookie发现身份认证信息已经加入到了Cookie中

再次访问/WeatherForecast/Get访问成功,说明登录起效了
如果删除Cookie再访问/WeatherForecast/Get返回401

以上,足以证明基于以上web应用程序基于Cookie的身份认证生效了

更多推荐

.net 基于Cookie的身份认证

本文发布于:2024-02-25 03:28:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1697628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份认证   net   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!