一 在program.cs中添加cookie认证
builder.Services.AddAuthentication( CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "auth"; options.ExpireTimeSpan = TimeSpan.FromDays(1); options.SlidingExpiration = false; options.LoginPath = "/Account/Login"; // 登录页面的路由 options.AccessDeniedPath = "/Account/AccessDenied"; // 访问被拒绝页面的路由 }); builder.Services.AddAuthorization();// 添加跨域 builder.Services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); });
二 相关接口
using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Authorise_Test_Demo.Controllers; [ApiController] [Route("api/[controller]/[action]")] 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] public IEnumerable<WeatherForecast> Weathers() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] [Authorize] public IEnumerable<WeatherForecast> Weathers_Authorize() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] [AllowAnonymous] public async Task Authenticate() { var claims = new List<Claim>{ new Claim(ClaimTypes.Name,"Bob"), new Claim(ClaimTypes.Role,"Admin") }; var authProperties = new AuthenticationProperties { // 可以设置Cookie的过期时间等属性 }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims,"my_identity"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new []{claimsIdentity}); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); } }
三 可以看到通过认证后,请求头会带cookie中的认证信息
4 uniapp上测试一下。
发现问题:
w3c规定,当请求的header匹配以下不安全字符时,将被终止,具体参考如下:
Accept-Charset Accept-Encoding Connection Content-Length Cookie Cookie2 Content-Transfer-Encoding Date Expect Host Keep-Alive Referer TE Trailer Transfer-Encoding Upgrade User-Agent Via
尝试方案1:
设置withCredentials
却发现如下问题:
1.uni.request设置withCredentials
2.仅H5支持
尝试方案2:
与后端协商之后,将cookie改为token
解决!