Auth0 Home Blog Docs

UnauthorizedError in Rule Returns 500 Server Error Instead of 401 Unauthorized

rules
authentication
extension
unauthorizederror

#1

I’m attempting to setup a custom Rule that authenticates a user based in the user’s group using the Authorization Extension. The custom rule uses the code snippet in Step 2 of the “Using Rules with the Authorization Extension” documentation. The client application is an ASP.NET Core 2 MVC project.

When a user attempts to authenticate into the client applicatoin and is not part of the required Group, the client callback URL (http://localhost:5982/signing-auth0) is displaying a 500 Server Error response with the message, “OpenIdConnectProtocolException: Message contains error: ‘unauthorized’, error_description: 'You are not authorized to access ', error_uri: ‘error_uri is null’.” While the message is what I expected because that’s the message I added to the rule, I would think the response code should be 401 Unauthorized, not a 500 Server Error.

The line of code responsible for the error is:

return callback(new UnauthorizedError('You do not have the required role to access ' + context.clientName));

Is there a way to return a 401 Unauthorized response when throwing an UnathorizedError exception so I don’t have to create an ugly hack in all my clients to determine the true error type to display a user-friendly message?

Update - 12/12/2017

I’m beginning to think the issue is caused by the .NET OpenIDConnect middleware and not an Auth0 issue. Below is a screen capture of the actual error I’m seeing at the callback URL location. The middleware is supposed to handle any calls to the callback URL (/signing-auth0) and is throwing a server error.
alt text
I tried adding event handlers for OnAuthenticationFailed and OnRemoteFailure for the OpenIDConnect middleware, but they don’t seem to be getting hit. So I’m still stumped as to how I can gracefully handle this “unauthorized” scenario.


#2

As you mentioned that is more the behavior of the OIDC middleware than anything related to Auth0. You should check this answer to a similar question, but that rule will just cause the Auth0 service to reply with an OAuth2 error response and it the middleware that is translating that to a 500.

Just switching the status code might also not be the best user experience and you should probably consider a redirect to another page (that page can still reply with a custom status code, but it should reply with some user friendly content also).


As additional note, the answer uses the OnMessageReceived because OnAuthenticationFailed does not seem to be applicable for this scenario and OnRemoteFailure also does not expose the exact error in a friendly API so I opted to handle that when a message is received and then check for an error.


#3

Thank you, jmangelo. The code snippet in the post you referenced was exactly what I was looking for… I can now easily redirect the user to a friendly “unauthorized” page.


#4