DonatoDeluxe
DonatoDeluxe
CC#
Created by DonatoDeluxe on 2/7/2024 in #help
Asp.Net 7.0 MVC Project - Authentication/Authorization
hey everyone junior-midlevel dev here i'm currently trying to implement a logic where a custom class "User" has a boolean "IsAdmin" and on user login, i want to check rights on different controllers with the iServiceCollection authentication. i know there is a IdentityFramework which is being used in many tutorials, but since the use case is much more simplistic, i want to simply login a user and check if it's an admin or not. what i did so far is, i've added the authentication and policy as following under "Program.cs"
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
options.LoginPath = "/Users/Login"
);

builder.Services.AddAuthorization(options =>
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"))
);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
options.LoginPath = "/Users/Login"
);

builder.Services.AddAuthorization(options =>
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"))
);
added the [Authorize(Policy = "AdminOnly")] attribute above the controller-classes which work so far so that i get redirected to the login page when i try to access a page with the authorization enabled. the thing is, that i don't know how i have to implement the logic, that in the login method, that the user get's actually logged in as an admin or not. i couldn't find anything helpful or something that would work yet... i'm using visual studio 2022 and it's an asp.net 7.0 MVC project thank you for your help in advance
48 replies