How to Secure .Net8 API Endpoint (Seperate controller Classes)

67 Views Asked by At

I have tried to follow https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-8.0 but it does not help me when my endpoints are in seperate controllers like so:

    namespace CompetencyApp.Api.Controllers
    {
    [Route("api/[controller]")]
    [ApiController]
    
    public class EmployeeController : Controller
    {
    private readonly IEmployeeRepository _employeeRepository;
    private readonly IWebHostEnvironment _webHostEnvironment;
    private readonly IHttpContextAccessor _httpContextAccessor;
    public EmployeeController(IEmployeeRepository employeeRepository, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)
    {
    _employeeRepository = employeeRepository;
    _webHostEnvironment = webHostEnvironment;
    _httpContextAccessor = httpContextAccessor;
    }
    
    [HttpGet]
    
    public IActionResult GetAllEmployees()
    {
    return Ok(_employeeRepository.GetAllEmployees());
    }

enter image description here Can anyone help at all. Thanks.

1

There are 1 best solutions below

0
Jalpesh Vadgama On

The documentation you are referring to is for the minimal apis if you want to use it for controllers then you need do like following

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

ConfigurationManager configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddDbContext<ApplicationDbContext>(
options => options.UseInMemoryDatabase("AppDb"));

// For Identity here aspnetusers for users and aspnetroels for roles
 builder.Services.AddIdentity<AspNetUser, AspNetRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

// Adding Authentication
builder.Services.AddAuthentication(options =>
{
   options.DefaultAuthenticateScheme = 
     JwtBearerDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = 
     JwtBearerDefaults.AuthenticationScheme;
   options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  })

// Adding Jwt Bearer
.AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = "your consumer URL i.e. angular app",
        ValidIssuer = "your API URL",
        IssuerSigningKey = new 
        SymmetricSecurityKey
       (Encoding.UTF8.GetBytes("your secret here")
     };
 });

 /// then configure your identity options
 builder.Services.Configure<IdentityOptions>(options =>
 {
     // User settings.
    options.User.RequireUniqueEmail = true;
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";

    // Password settings.
    options.Password.RequireDigit = true;
   options.Password.RequireLowercase = true;
   options.Password.RequireNonAlphanumeric = true;
   options.Password.RequireUppercase = true;
   options.Password.RequiredLength = 6;

    // Lockout settings.
    //options.Lockout.MaxFailedAccessAttempts = 3;
    //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
  });


  builder.Services.AddControllers();
  builder.Services.AddAuthorizationBuilder();

This is just a sample thing but you search with asp.net core with jwt authentication with asp.net identity you will get lots of example.