Hi
I use asp net core mvc 3.1, with cookie autentication..
But when I add [Authorize] in each control, it redirect to login althought the browser send the cookie.
I followed this link...
https://www.c-sharpcorner.com/article/cookie-authentication-in-net-core-3-0/
This is the startup class:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Autofac; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Pronabec.IES_EXTRANET_INTERNO.Presentation.SITE.Filters; using Pronabec.IES_EXTRANET_INTERNO.Presentation.Util.Dto; using ServiceReferenceTarifario; namespace Pronabec.IES_EXTRANET_INTERNO.Presentation.SITE { 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.AddMvc( options => options.Filters.Add(new PronabecErrorAttribute()) ); //.SetCompatibilityVersion(CompatibilityVersion.Version_3_0); //.AddNewtonsoftJson(); services.AddAuthentication(options => { options.DefaultScheme = "CookieAuthentication"; options.RequireAuthenticatedSignIn = false; }) .AddCookie("CookieAuthentication", config => { config.Cookie.Name = "UserLoginCookie"; config.LoginPath = "/Account/Login"; config.SlidingExpiration = true; }); //services.AddAuthentication("CookieAuthentication") // .AddCookie("CookieAuthentication", config => // { // config.Cookie.Name = "UserLoginCookie"; // config.LoginPath = "/Account/Login"; // }); services.AddControllersWithViews(); services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache services.AddSession(); services.AddSingleton(x => new ServiciosDto { TarifarioUrl = Configuration["UrlServicios:Tarifario"], MaestrosUrl = Configuration["UrlServicios:Maestros"], SeguridadUrl = Configuration["UrlServicios:Seguridad"], ImagenUrl = Configuration["UrlServicios:Imagen"], UsuarioUrl = Configuration["UrlServicios:Usuario"], ArchivosUrl = Configuration["UrlServicios:Archivo"] }); services.AddSingleton(x => new AppSettingsDto { IdSistema = Configuration["AppSettings:ID_SISTEMA"] }); services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterModule(new ApplicationModule()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSession(); app.UseHttpsRedirection(); app.UseStaticFiles(); //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), "Content")), // RequestPath = "/Content" //}); //app.UseDirectoryBrowser(new DirectoryBrowserOptions //{ // FileProvider = new PhysicalFileProvider( //Path.Combine(Directory.GetCurrentDirectory(), "Content")), // RequestPath = "/Content" //}); app.UseRouting(); // who are you? app.UseAuthentication(); // are you allowed? app.UseAuthorization(); //app.UseEndpoints(endpoints => //{ // endpoints.MapControllerRoute( // name: "default", // pattern: "{controller=Account}/{action=Login}/{id?}"); //}); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Account}/{action=Login}/{id?}"); }); } } }
The method which creates the cookie...
var identity = new System.Security.Claims.ClaimsIdentity(new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, Username) }); var nameSis = appSettingsDto.IdSistema; var objUser = await agenteSeguridad.getRoles(Username, nameSis); foreach (var rol_ in objUser) { identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, rol_.Name)); } var principal = new System.Security.Claims.ClaimsPrincipal(identity); await HttpContext.SignInAsync("CookieAuthentication", principal);
I can get the values of the cookie but I have to write "anonymous" in each method..
[HttpGet] [AllowAnonymous] public ActionResult RedirectToDefault() { var userIdentity = (System.Security.Claims.ClaimsIdentity)HttpContext.User.Identity; var claims = userIdentity.Claims; var roleClaimType = userIdentity.RoleClaimType; var rolesc = claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).ToList(); String[] roles = rolesc.Select(c => c.Value).ToArray(); if (roles.Contains("ADMINISTRADOR-IES/CF")) { return RedirectToAction("Index", "Home"); } if (roles.Contains("ADMINISTRADOR-PRONABEC")) { return RedirectToAction("Index_admin", "Home"); } return RedirectToAction("Index", "Home"); }
But If I write [Authorize] in a method, the web is redirect to the login..