I have a very basic web API controller within an identity server project:
namespace Project.IDP.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Test()
{
return Ok("Test");
}
}
}
If I call this controller via Postman I receive an OK response 200 and the content 'Test', great.
However, if I add the Authorize attribute I receive HTML! The HTML is the login page of Identity Server. However, I have authorized and I'm passing the access token within the request (all via postman)
namespace Project.IDP.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Test()
{
return Ok("Test");
}
}
}
My client is setup like this:
new Client { ClientId= "m2m", ClientName = "Machine 2 Machine Client", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { IdentityServerConstants.LocalApi.ScopeName, "myapi.mi_test" } },
the API is like this:
new ApiResource[]
{
new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
new ApiResource("myapi", "My API" )
{
Scopes = new List<Scope>
{
new Scope("myapi.mi_test", "MI Access")
}
}
};
In my startup class have tried:
services.AddLocalApiAuthentication();
and
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:31101";
options.ApiName = "myapi";
});
But I can't get it to work, what am I missing?
I have a similar setup, the only difference is that you need to specify the specific auth policy in your Authorize attribute. In your "MyController" change your Authorize attribute to:
[Authorize(LocalApi.PolicyName)]
This requirement is shown in the IdenityServer docs at:
https://identityserver4.readthedocs.io/en/latest/topics/add_apis.html