I have a simple REST API server with authentication based on OAuth2. Everything works as expected and I’m able to call the controllers by setting the correct bearer token. My goal is to manage authorization entirely and to do this, I wanted to use the Microsoft.AspNetCore.Identity class. However, as soon as I add the related configuration to my program.cs, the calls to the controller fail.
This is my program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is my simple controller class:
[Route("api/[controller]")]
[ApiController]
public class OAuthTestController : ControllerBase
{
[HttpGet("public")]
public IActionResult GetPublicData()
{
return Ok("This is public data.");
}
[HttpGet("protected")]
[Authorize]
public IActionResult GetProtectedData()
{
return Ok("This is protected data, you are authenticated.");
}
}
If I try to call the GetProtectedData() endpoint using PostMan, the request is redirected to a login page that does not exist, and therefore I receive a 404 error. Is it possible to use OAuth2 and Microsoft.AspNetCore.Identity together? Is it better to manually create the tables to save users and roles?