Search code examples
c#.net.net-coreidentityserver4

C# .Net Core API Authorized route with Identity Server 4


I have an API which is using Identity Server 4 and register and login routes work. But the ones which I protect with [Authorized] give me 404 with or without Authorization header. If I remove [Authorized] from route, it get's hit right. What might be the problem?

This is the controller:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Security.API.Controllers
{
    [Route("[controller]")]
    public class AccountController : Controller
    {
        private readonly IAccountService accountService;

        public AccountController(IAccountService accountService)
        {
            this.accountService = accountService;
        }

        [HttpGet("")]
        public string Get()
        {
            return "You are seeing this because account controller is working fine!";
        }

        [Authorize]
        [HttpGet("getauthorized")]
        public string GetAuthorized()
        {
            return "This is authorized okay.";
        }
...

First route get's hit, second one doesn't


Solution

  • you need to put the [Authorize] attribute on the Relying party, means your web app which is calling the web apis. Identity server secure your web apis by token authentication.

    • Put [Authorize] on the client app (RP)
    • It will be redirected to auth server login/register
    • After successful login, will be redirected to client app
    • here get the access token and call your api