wiem
wiem

Reputation: 47

ASP.NET Core JWT Authentication to secure webAPI [Authorize] attribute Error 401 Unauthorized

I develop API POST and it works correctly, but when I add [Authorize] attribute I got 401 Unauthorized in the postman even when I add token correct in header

 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
           
            [HttpPost]
            
            public async Task<ActionResult> Post([FromBody] CViewModel cVM)
            {
    // to do
            }

I just want to secure my API with JWT TOKEN, API authentication work correctly and generate a token but I can't figure why when I added [Authorize] attribute I got Error 401 Unauthorized in my POST API.

THANKS!

Upvotes: 0

Views: 383

Answers (2)

wiem
wiem

Reputation: 47

the problem is I used different secret key in the startup and generate token method

Upvotes: 0

Karney.
Karney.

Reputation: 5031

When you add [Authorize], this action can only be successfully accessed if the token is carried. One of possibilities is that the url is not mathced with this route. But a more important reason is that you do not configre the login path correctlly, or the login path does not exist. So you could check the configuration in startup.

Upvotes: 0

Related Questions