I wrote a website that will do a SSO from Discord. I am trying to do a login system using only that by way of cookies. I seem to not be able to set the cookie and return User.Identity.IsAuthenticated;
as true. When I look at the browser using F12, the cookie is not present. I am unsure why the cookie is not being sent to the user after logging in. I have provided below the Startup.cs and my login file. Thank you in advance!
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 = ""});
}
}
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?}");
});
}
}
}
SignInAsync(HttpContext, ClaimsPrincipal) Sign in a principal for the default authentication scheme. The default scheme for signing in can be configured using DefaultSignInScheme.
Let's implement the Cookie Authentication in ASP.NET Core step by step. Open the Visual Studio and click on Create a new Project. Select ASP.NET Core Empty project and click on next. Give a name to your Project, select the location for the project creation, and click on Next.
AuthenticationScheme passed to AddAuthentication sets the default authentication scheme for the app. AuthenticationScheme is useful when there are multiple instances of cookie authentication and the app needs to authorize with a specific scheme. Setting the AuthenticationScheme to CookieAuthenticationDefaults.
Net core 2.1 or higher on is built-in supports GDPR (General Data Protection Regulation).
and until you accept the cookie, cookie does not set in the browser.
add this following code to ignore 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;
});
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";
});
the options.ConsentCookie.IsEssential = true;
ignored GDRP and allows cookies to be set in the browser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With