使用.NET CORE自带Authorize

发布时间:2022-04-03 18:05:18来源:本站阅读(576)

    .NET一直有自带Authorize验证,在FRAMEWORK时就一直使用,方便好用。

    下面说下在.NET CORE中的使用,使用COOKIES验证

    首先看下program的代码 

    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
    {
        o.LoginPath = new PathString("/Home/Admin");
        o.LogoutPath = new PathString("/Home/Admin");
        o.AccessDeniedPath = new PathString("/Home/Admin");
        o.Cookie.HttpOnly = true;
        o.ExpireTimeSpan = new TimeSpan(8, 0, 0);
    });
    app.UseAuthentication();
    app.UseAuthorization();

    然后看下登录的后台代码

    var user = _admin.Value.Login(u, p);
    
    var claims = new List<Claim> { new Claim("adminUser", JsonSerializer.Serialize(user)) };
    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    var adminUser = new ClaimsPrincipal(claimsIdentity);
    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, adminUser).Wait();

    最后在要验证的 controller或action上面加下以下代码

    [Authorize(AuthenticationSchemes= CookieAuthenticationDefaults.AuthenticationScheme)]

    OK,搞定

    注意:Authorize 后面括号里的一定要加

关键字Authorize

上一篇: lambda中使用SUM

下一篇: .NET6 WEB API使用JWT