Search code examples
c#asp.net-corehttpsannotations

Do I use [Authorize] annotation?


I have a web application in which you can register with the given data (username, password). Then a JWT token is built using this data and stored in the session using the jwt-token key. Also I have for example the main page of my application, I want an authorized user to be able to go to this resource using only a query input in the browser. Here is my code:

app.MapGet("/home", [Authorize]() => {
    // return my page
});

But to go to such a resource in the request must specify Authorization header with jwt token, it turns out that just writing in the browser “www.mywebsite/home” will not be able to go to the page /home because I did not pass this header, I solved this problem by adding jwt token in the session and when going to the page /home check its presence and correctness.

So my question is, should I use the [Authorize] annotation in my case, or what did I do wrong?


Solution

  • You could use:

    app.MapGet("/home", () => {
        // return my page
    }).RequireAuthorization();
    

    Have a look in the docs for more details (including JWT).