C
C#3mo ago
ToeKnee

Authorization doesn't work as it should ASP.NET C#

I'm currently doing an api for cloth shopping assignment and my problem is that any user can create an order when they are not authorized. But to be authorized you need to send a token. Maybe it's easier to send the github link: https://github.com/Ynot-TT/TopApi.git
GitHub
GitHub - Ynot-TT/TopApi
Contribute to Ynot-TT/TopApi development by creating an account on GitHub.
3 Replies
Pobiega
Pobiega3mo ago
first things first: please please add a .gitignore file to your project root level. you can generate one with dotnet new gitignore this will prevent you from adding files that do not belong in git, like build artifacts (bin/obj folders) etc regarding your actual error, can you be more specific? I see you have an authorize attribute on your order controller, but you say its accessible without being logged in? Is that correct?
ToeKnee
ToeKnee3mo ago
Yes that is correct, the user can make an order which should not be possible only when being logged in. - An order must be able to be created which consists of a number of products. To make this the user must be logged in ie it must be sent with a token to the method must be executable.
Pobiega
Pobiega3mo ago
upon closer inspection, you dont set a default authentication schema then again, I replicated that and it works fine on my end. just setting [Authorize] on a controller correctly gives 401 back
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
.AddJwtBearer();

builder.Services.AddAuthorization();
...

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// controller
[ApiController]
[Route("api/[controller]")]
[Authorize]
public sealed class TestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Hello from TestController");
}
}
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
.AddJwtBearer();

builder.Services.AddAuthorization();
...

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// controller
[ApiController]
[Route("api/[controller]")]
[Authorize]
public sealed class TestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Hello from TestController");
}
}
this works as expected, I get 401 here works fine when adding some actual token validation params (that mirror yours) and fixing up a way to get a token ie, I get 401 without token, get 200 with a valid token