首页 > 其他分享 >uniapp-net core后台-实现认证

uniapp-net core后台-实现认证

时间:2023-09-14 22:23:55浏览次数:37  
标签:uniapp core builder public Summaries new using net options

一 在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

解决!
 

标签:uniapp,core,builder,public,Summaries,new,using,net,options
From: https://www.cnblogs.com/Insist-Y/p/17703616.html

相关文章

  • .Net多线程读取pdf文本
    1.nuget安装UglyToad.PdfPig2.SemaphoreSlimsemaphore=newSemaphoreSlim(10);同时启动10个线程读取指定页面文本。C#代码:staticstringGetPdfText(stringfilePath){FileInfofile=newFileInfo(filePath);if(file.Extension.ToLower().Contains("pdf"))......
  • 流量分析工具 NetCap
    项目地址:https://github.com/dreadl0ck/netcap/tree/masterTheNetcap(NETworkCAPture)frameworkefficientlyconvertsastreamofnetworkpacketsintoplatformneutraltype-safestructuredauditrecordsthatrepresentspecificprotocolsorcustomabstractions......
  • .NET 程序员的调试神器-Dumpify
    DumpifyDumpify是一个使用C#开发的开源库,它通过向控制台应用程序添加.Dump()扩展方法来提高工作效率和可调试性。可以Dump任何对象并以结构化且丰富多彩的方式输出到控制台、跟踪、调试事件。支持属性、字段和非公共成员,支持设置最大嵌套层数,支持循环依赖和引用,支持......
  • .NET Core创建API项目
    新建项目类型:ASP.NETCoreWebAPIWebAPI控制器通常应派生自ControllerBase而不是Controller。Controller派生自ControllerBase,并添加对视图的支持,因此它用于处理Web页面,而不是WebAPI请求。如果同一控制器必须支持视图和WebAPI,则派生自Controller。API接口返回......
  • C# 性能诊断工具 dotnet-counters 的使用
    创建.NET程序Dump的几种姿势下载dotnet-counters工具简介dotnet-counters是一个性能监视工具,用于初级运行状况监视和性能调查。它通过EventCounterAPI观察已发布的性能计数器值。例如,可以快速监视CUP使用情况或.NETCore应用程序中的异常率等指标安装通过nuget包安装:......
  • 核桃云监控:https://jk.htyun.net/
    今天给大家推荐一款非常好用的网站监测平台,也是我一直再用的,它就好比给自家的网站上雇了一个管家,它可以替我24小时不间断端的扫描网站,如果出现宕机,或者因为网络还是其他问题打不开时,系统会自动发送报警来提醒我,这样就节省了我的大部分时间,而我就不用时不时去自己去登录网站检查了,......
  • P-Core vs E-Core
    P-Core在英特尔的两种不同核心布局中,P-Core是芯片上最强的核心。这些将消耗最多的能量,以最高的时钟速度运行。P-Core通常会处理较重的任务,例如游戏或更重的处理负载,以及通常受益于单核性能的其他工作负载。而过去,英特尔芯片上的内核全部相同时,PC的所有指令均等分配在所有......
  • PentestGPT:A GPT-empowered penetration testing tool
    一、WhatisPentestGPT?PentestGPT是一种由大型语言模型(LLMs)赋能的渗透测试工具。它旨在自动化渗透测试过程。它基于ChatGPT构建,并以交互模式运行,以指导渗透测试人员在整体进展和具体操作上。GeneralDesignPentestGPT提供了一个统一的终端输入处理程序,并由三个主要组件支持:......
  • netcore请求json斜杠带空格导致请求报错
    我用netcore发布了一个webapi接口,个别电脑,同样的浏览器(谷歌),swagger调用接口的时候,它的json体会加空格,然后请求就会报错。这是控制器里的方法下图是请求输入: 下图是加了空格的请求内容,如红色框所示,带了空格 下图是报错的内容下图是正常请求的内容,可以返回想要的结果......
  • How to fix java.net.SocketException: Too many files open in tomcat
    NotmanyJavaprogrammersknowsthatsocketconnectionsaretreatedlikefilesandtheyusefiledescriptor,whichisalimitedresource.Differentoperatingsystemhasdifferentlimitsonnumberoffilehandlestheycanmanage.Oneof......