Search code examples
asp.net-coreidentityserver4

Identity Server 4: 401 instead of redirect for specific controllers


I'm adding a couple of controllers to my Identity Server 4 asp.net core mvc app. To be clear, I have added these to the IdentityProvider app (which I use for SSO), not a client app.

When I send a request to my endpoint (ex. GET sso.app.com/api/users) and I'm not authenticated, I get redirected to my login page, otherwise it works just fine. I would like to intercept the redirect and have the controller return a 401 Unauthorized instead.

I've explored using a policy for the Authorize header, but that only gives me a pass/fail based on an already authenticated user, so I don't have enough control there. I read on another similar SO question that the aspnet core team doesn't want devs to extend the Authorize header, but use policies instead.

I poked around and didn't find any obvious options for this when adding the service in Startup either. Are there any options that let me set behavior for specific paths/endpoints such as '/api'?


Solution

  • Comment copied to an answer:

    So you have three apps here? Identity Server, some Identity Provider (IDP) with the API, and a client? Or are you referring to Identity Server as the IDP (which is fine, sometimes it is, sometimes it isn't)?

    But if I understand your setup, the redirect to login should receive the API endpoint as the return URL. Just inspect that in your login controller and return a 401 if the URL matches the endpoints that you want to block.

    I don't think you can do interception elsewhere inside Identity Server.