.net 基于Cookie的身份认证
身份认证Authentication,用于认定用户是谁
鉴权Authorization,用于校验用户是否有访问某东西的权限
新建一个asp.net core web api项目
注册基于Cookie的身份认证服务
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
//重写身份认证失败的逻辑,默认是跳转到/Account/Login,这里改为直接返回401
options.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 _logger;
public WeatherForecastController(ILogger logger)
{
_logger = logger;
}
[HttpGet]
[AllowAnonymous]//允许匿名访问
public object Login()
{
List claims = new List
{
//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 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的身份认证生效了



