Luk*_*lsh 5 c# asp.net-core asp.net-core-3.0
我写了一个网站,可以从 Discord 进行 SSO。我正在尝试通过 cookie 仅使用登录系统。我似乎无法设置 cookie 并返回User.Identity.IsAuthenticated;true。当我使用 F12 查看浏览器时,cookie 不存在。我不确定为什么登录后没有将 cookie 发送给用户。我在 Startup.cs 和我的登录文件下方提供了。先感谢您!
public class SigninController : Controller
{
private ApplicationDbContext _context;
public SigninController(ApplicationDbContext context)
{
_context = context;
}
[AllowAnonymous]
public async Task<RedirectToActionResult> SaveRegistration(RegistrationViewModel pageData)
{
var debug = User.Identity.IsAuthenticated;
if (pageData.Tribe == null)
{
pageData.Tribe = "Solo";
}
//Create the nomad
var nomad = new Nomad
{
Name = pageData.Name,
Role = "user",
Snowflake = pageData.Snowflake,
Tribe = pageData.Tribe
};
//Add and save the nomad to the database
_context.Nomads.Add(nomad);
await _context.SaveChangesAsync();
//Generate the claims
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, nomad.Name));
claims.Add(new Claim("Snowflake", nomad.Snowflake.ToString()));
claims.Add(new Claim("Tribe", nomad.Tribe));
claims.Add(new Claim(ClaimTypes.Role, nomad.Role));
//Generate the user's cookie!
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties { IsPersistent = true };
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
debug = User.Identity.IsAuthenticated;
return RedirectToAction("Index", "Home", new {Area = ""});
}
}
Run Code Online (Sandbox Code Playgroud)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Last_Oasis_Web_Suite.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace A_Name_Space
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.Name = "Cookie";
options.LoginPath = "/Discord/Signin/Redirect";
options.LogoutPath = "/Discord/Signout";
});
services.AddControllers(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
Net core 2.1 或更高版本内置支持 GDPR(通用数据保护条例)。
并且在您接受 cookie 之前,cookie 不会在浏览器中设置。
添加以下代码以忽略 GDPR
services.Configure<CookiePolicyOptions>(options =>
{
options.ConsentCookie.IsEssential = true;
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
Run Code Online (Sandbox Code Playgroud)
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.IsEssential = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.Name = "Cookie";
options.LoginPath = "/Discord/Signin/Redirect";
options.LogoutPath = "/Discord/Signout";
});
Run Code Online (Sandbox Code Playgroud)
在options.ConsentCookie.IsEssential = true;忽略GDRP并允许使用Cookie在浏览器中设置
答案是我没有配置为在 ASP.NET 中使用 HTTPS,因此 cookie 永远不会发送到浏览器。我重新制作了我的项目并选中了强制使用 HTTPS 的框,一切正常。我假设没有安全连接来发送加密数据,它决定不发送它。
| 归档时间: |
|
| 查看次数: |
3948 次 |
| 最近记录: |