Estoy haciendo una aplicación Blazor WASM con netcore 7 con cuentas individuales de google y tengo el siguiente problema en modo producción (como siempre en modo depuración todo funciona).
Mi aplicación genera el menú lateral en función de los roles. Cuando entro por primera vez en la aplicación, meto el email de google, autentifica bien y funciona correctamente. El problema viene cuando le doy a cerrar sesión y vuelvo a meter el email de google, la cuenta entra bien, pero los métodos para recuperar el role me dicen que tiene que no está permitido porque el usuario no está autentificado y la única forma de hacer que vuelva a funcionar es pulsando CRT+F5 o borrando los datos del navegador.
Este es el error:
info: System.Net.Http.HttpClient.GestionAlumnosAM.ServerAPI.LogicalHandler[100]
Start processing HTTP request GET https://dominio.net/api/Roles/ _bound_js_globalThis_console_info:7
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
Mi program.cs del server:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDbContext<J2GestionAlumnosContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession
(options =>
{
//options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
builder.Services.AddIdentityServer(options =>
{
options.LicenseKey = "clave";
})
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
builder.Services.AddAuthentication()
.AddIdentityServerJwt()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = "cliente";
googleOptions.ClientSecret = "clave";
})
.AddJwtBearer(options =>
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
System.Text.Encoding.UTF8.GetBytes("ASKL3KJ4NKJ4NKJSFNSKDJFNSDKJ4JNK4NKSJNSDKJFNSDK")),
ClockSkew = System.TimeSpan.Zero
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();//para usuario
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseSession();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
Y en NavMenu.razor:
protected override async Task OnInitializedAsync()
{
if (profesor == null)
await GeneraPermisos();
}
private async Task GeneraPermisos()
{
try
{
List<string> permisos = await Http.GetFromJsonAsync<List<string>>("/api/Roles/");
if (permisos!=null)
{
if (permisos.Count() > 0)
{
for (int i = 0; i < permisos.Count; i++)
{
if (permisos[i] == "Profesor")
profesor = true;
if (permisos[i] == "Tutor")
tutor = true;
if (permisos[i] == "Directivo")
directivo = true;
if (permisos[i] == "Internado")
internado = true;
}
}
}
}
catch (AccessTokenNotAvailableException exception)
{
//exception.Redirect();
error = "ERROR" + exception.ToString();
}
}
Y en la llamada a List permisos = await Http.GetFromJsonAsync<List>("/api/Roles/"); es donde salta el error inicial y no genera el menú
Para autenticar el usuario, he añadido el Area->ExternalLogin y he modificado el método OnGetCallbackAsync
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Login", new
{
ReturnUrl = returnUrl
});
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information.";
return RedirectToPage("./Login", new
{
ReturnUrl = returnUrl
});
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
string idUser = info.Principal.FindFirst(ClaimTypes.Email).Value;
// string idUser = ((ClaimsPrincipal)HttpContext.User).FindFirst(ClaimTypes.NameIdentifier).Value;
HttpContext.Session.Set("Email", Encoding.ASCII.GetBytes(idUser));
string Id = _context.Profesores.First(p => p.Email == idUser).Id;
HttpContext.Session.Set("Id", Encoding.ASCII.GetBytes(Id));
AspNetUser usuario = _context.AspNetUsers.First(p => p.Email == idUser);
var user = _userManager.Users.First(p => p.Id == usuario.Id);
if (await _userManager.IsInRoleAsync(user, "Profesor"))
HttpContext.Session.SetInt32("Profesor", 1);
else
HttpContext.Session.SetInt32("Profesor", 0);
if (await _userManager.IsInRoleAsync(user, "Tutor"))
HttpContext.Session.SetInt32("Tutor", 1);
else
HttpContext.Session.SetInt32("Tutor", 0);
if (await _userManager.IsInRoleAsync(user, "Directivo"))
HttpContext.Session.SetInt32("Directivo", 1);
else
HttpContext.Session.SetInt32("Directivo", 0);
if (await _userManager.IsInRoleAsync(user, "Internado"))
HttpContext.Session.SetInt32("Internado", 1);
else
HttpContext.Session.SetInt32("Internado", 0);
_logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToPage("./Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ReturnUrl = returnUrl;
ProviderDisplayName = info.ProviderDisplayName;
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
Input = new InputModel
{
Email = info.Principal.FindFirstValue(ClaimTypes.Email)
};
}
return Page();
}
}
El /api/Roles/ es:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using GestionAlumnosAM.Shared.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using IdentityModel;
using GestionAlumnosAM.Server.Models;
using GestionAlumnosAM.Server.Helpers;
namespace GestionAlumnosAM.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class RolesController : ControllerBase
{
private readonly J2GestionAlumnosContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public RolesController(J2GestionAlumnosContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_context = context;
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
ClaimsPrincipal user = (ClaimsPrincipal)HttpContext.User;
if (user == null)
return Ok();
var obj = user.FindFirst(ClaimTypes.NameIdentifier);
if (obj == null)
return Ok();
string idUser = obj.Value;
if (idUser == null)
return Ok();
AspNetUser usuario = await _context.AspNetUsers.Where(p => p.Id == idUser).FirstAsync();
var dato = _userManager.Users.First(p => p.Id == usuario.Id);
var rolesList = await _userManager.GetRolesAsync(dato).ConfigureAwait(false);
return rolesList.ToList();
}
}
Alguna idea?
Gracias
/api/Roles/
tienes puesto que solo ingresen usuarios autorizados algo como[Authorize]
y por eso te da error ahí. Pero el error de fondo está en otro lado, es que el login no autentifica (tal como dices en tu último comentario), entonces deberías mostrar el código que hace ese trabajo, junto con mostrar como haces ellogout