How to set up [Authorize] attribute with Aspnet.core.Components.Authorization?
Hi, I put the Login/logout function in my application with Aspnet.core.Components.Authorization which means that when the person creates an account they can have access to the whole application.
I would like to introduce the [Authorize] attribute in specific controller.
I follow-up this link but it doesn't work https://learn.microsoft.com/fr-fr/aspnet/core/security/authorization/simple?view=aspnetcore-7.0
If I follow the recommendation I've put the [Authorize] attribute as follow
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdtPageController : ControllerBase
{
private readonly ApplicationDbContext _context;
public AdtPageController(ApplicationDbContext context)
{
this._context = context;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var devs = await _context.ADTs.ToListAsync();
return Ok(devs);
}
...
}
Normally this would specify that I don't have access to this controller. This is not the case! How can I limit access?
Plus, I would like to know how to create an account with access to the entire application.
Thanks in advance
Developer technologies | .NET | Blazor
-
AgaveJoe • 30,126 Reputation points
2023-06-17T11:33:10+00:00 Normally this would specify that I don't have access to this controller. This is not the case! How can I limit access?
If I understand the [Authorize] attribute allows an anonymous user to access the Web API Controller, AdtPageController.
I've seen this situation when the application is configured for multiple authentication schemes but no default scheme is set. This problem can also happen if the middleware is not in the correct order.
Unfortunately, you've provided no information regarding how security works or how the Blazor and Web API are hosted. At this point we can only guess what's wrong.
Perhaps reading the official documentation will help.
-
sblb • 1,231 Reputation points
2023-06-17T14:54:41.22+00:00 you will find below the programm.cs
// Add services to the container. builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = false; options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return Task.CompletedTask; }; });
I've seen your link and If I understand I have to add the scheme
e.g
builder.Services.AddAuthentication() .AddCookie(options => { options.LoginPath = "/AdtPageController/Unauthorized/"; options.AccessDeniedPath = "/AdtPageController/Forbidden/"; }) .AddJwtBearer(options => { options.Audience = "http://localhost:5001/"; options.Authority = "http://localhost:5000/"; });
Is that right?
Can you please help me to understand?
-
AgaveJoe • 30,126 Reputation points
2023-06-17T16:18:39.25+00:00 Can you please help me to understand?
It is impossible to answer your question as it is still unclear how you designed the security.
The incomplete first code snippet indicates you are using cookie authentication while the second suggests that you are using cookie authentication and JWT.
If you are using cookie authentication only, did you make sure the authentication cookie did not exist before calling Web API? Did you do any debugging to make sure the request was actually not authenticated?
If you are using cookie and JWT authentication then you really need to read the entire linked documentation. Later in the documentation is has example code that uses an attribute to select the authentication type for Web API.
For the second time, explain how the security is designed rather than forcing the community to guess.
-
sblb • 1,231 Reputation points
2023-06-18T10:56:23.2+00:00 how you designed the security.
If you have understand I'm here if someone can help me to define the security.
By security I understand :
_ Authentication
_Authorisation
I use Microsoft.Aspnet.core.Components.Authorization
During the Authentication I've defined class models
CurrenUser
,LoginRequest
andRegisterRequest
and after that the migration I obtainThis means all things works well to Login/Register
So Right now I would like to add a role Admi and user to limit some acces to Razor Pages.
Have you any suggestions?
-
AgaveJoe • 30,126 Reputation points
2023-06-18T12:47:19.2566667+00:00 If you have understand I'm here if someone can help me to define the security.
For the third time, we need to know how your security works to answer this question. Did you secure Web API with a JWT or Cookie? You should know the answer to this question since this is your code.
The following is example MVC code that adds a role to the roles table using the RoleManager API that comes with Identity. A SQL script or migrations works as well.
public class RoleController : Controller { private readonly RoleManager<IdentityRole> _roleManager; private readonly UserManager<IdentityUser> _userManager; public RoleController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager) { _roleManager = roleManager; _userManager = userManager; } // GET: RoleController public ActionResult Index() => View(_roleManager.Roles); // POST: RoleController/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(string Name) { try { if (!string.IsNullOrEmpty(Name)) { if (!(await _roleManager.RoleExistsAsync(Name))) { await _roleManager.CreateAsync(new IdentityRole(Name)); return RedirectToAction("Index"); } } return View(); } catch { return View(); } }
Use the UserManager API to assign a role to a user. If you implemented cookie authentication and used the SignInManager API to generate the auth cookie then the role is persisted in the cookie. If you are using a JWT then you'll need to add the role to the token. Again, we cannot see your code and have no idea how you designed the security.
public async Task AddRole(string Role) { var user = await _userManager.FindByNameAsync(User.Identity.Name); var results = await _userManager.AddToRoleAsync(user, Role); return; }
-
Anonymous
2023-06-20T03:12:08.0233333+00:00 Hi @sblb
From your previous sharing, we know you are using Asp.net core Identity to manage user and role, but as AgaveJoe said it is still not clear about how your security works. So, can you share all of the code in the Program .cs? Besides, whether your project is an MVC, Blazor server or Blazor WebAssembly application (whether it is Asp.net Hosted or not?)?
-
sblb • 1,231 Reputation points
2023-06-20T05:31:33.44+00:00 Hi, I used Blazor wasm asp.net hosted.
You will fin blow the program.cs.
using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Radzen; using Microsoft.EntityFrameworkCore; using FollowUpDash.Server.Data; using FollowUpDash.Client.Services; using FollowUpDash.Server.Models; using Microsoft.AspNetCore.Identity; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = false; options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return Task.CompletedTask; }; }); builder.Services.AddControllers().AddNewtonsoftJson(); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { 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.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.MapControllers(); app.MapFallbackToFile("index.html"); app.Run();
-
AgaveJoe • 30,126 Reputation points
2023-06-20T10:07:48.1+00:00 Is your first question is resolved? Anonymous users cannot access the Web API controller? This is a second question where you are asking how to implement role based authorization using Identity?
As already explained with source code, the RoleManager API handles CRUD operations with the role table. The UserManager API manages user roles and claims.
The SignInManger logs the user in and automatedly adds any user roles and/or claims to the token stored in the authentication cookie. Unfortunately you did not provided the code that logs in the user so we still have no idea how the login code works. A common approach is the Blazor WASM application is unloaded and redirected to a login form, MVC or Razor Pages hosted in the same application, when a secured resource is requested. The user logs in and is redirected back to the Blazor WASM application with the authentication cookie.
From this point you can use Role and Claim based authorization on the Web API controller(s).
Role-based authorization in ASP.NET Core
Claims-based authorization in ASP.NET Core
For Blazor authorization.
ASP.NET Core Blazor authentication and authorization
Can you explain how your security is designed? In other words, when you were thinking about this application how did you intent authentication and authorization to work?
Perhaps you followed a tutorial and do not understand the tutorial? If so, provide a link to the tutorial or ask the tutorial author for assistance.
-
Deleted
This comment has been deleted due to a violation of our Code of Conduct. The comment was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
-
AgaveJoe • 30,126 Reputation points
2023-06-20T17:59:18.5966667+00:00 I provided sample code to add roles the roles table and code to assign roles to users. If you are having a problem with the RoleManager or UserManager then share the code you've written.
If I understand correctly, the other part of your ever expanding use case is a way to limit account creation to a list of users. The community cannot answer his question. We have no idea what bits of information you have to identity users that can create accounts.
-
sblb • 1,231 Reputation points
2023-06-20T19:21:35.4066667+00:00 We have no idea what bits of information you have to identity users that can create accounts.
Only mail address and names.
If in my authorisation table I defined the user can access
eg I have A, B C with a.terre@cosmos.terre b.terre@cosmos.terre c.terre@cosmos.terre I can limit access, no?
I'll look into it and get back to you.
-
Anonymous
2023-06-22T09:50:10.5133333+00:00 Hi @sblb
I found some relates articles about secure a hosted ASP.NET Core Blazor WebAssembly app, you can refer to them:
This link will use Identity Server to authenticate users and API calls:
Secure a hosted ASP.NET Core Blazor WebAssembly app with Identity Server
The following links will use Asp.net core identity to achieve it.
blazor-series - Blazor WebAssembly Authentication with ASP.NET Core Identity
Sign in to comment