JSS: Layout service 401 and unauthorized access denied bug
I wanted to implement access denied handling in my JSS app, but API-calls through Layout Service for restricted-access routes are redirected to /sitecore/service/notfound.aspx... Let's see what we can do about this.
In the bootstrapped JSS app (at least the React one) there is no handling for access denied responses like 401, 403 etc. I wanted to see how this could be done and started messing with the read rights of the user thats connected to the API key my app uses. Which leads us to the issue.
If the visitor tries to access a route that they do not have read access to, the request is redirected to /sitecore/service/notfound.aspx, which of course causes an error since the jss app is expecting a JSON response from the layout service. This is of course not the expected behaviour. Instead, I would have expected the request to return a 401 or a 403 response.
I communicated this issue to the JSS team. Turns out it's due to the identity server not recognizing that this an ajax request, and therefore it redirects to notfound.aspx. If you are not using identity server and instead is working the the old forms authentication, you won't experience this issue.
EDIT: Got some good input from fellow JSS enthusiast Vitalii Tylyk regarding this, namely that this issue is not specific to setups using identity server, but affects any OWIN-based authentication (in this context meaning Sitecore Federated Auth).
The good news is, there are a couple of workarounds to solve this, which Adam Weber suggested to me in the github issue I wrote. Instead of just copying it here, I'll provide you with the link and you can read straight from the source yourselves.
Github Issue 145: https://github.com/Sitecore/jss/issues/145#issuecomment-459092096
The solution (or rather, the workaround)
For your information, I went with the second approach (the custom processor one) suggested by Adam in my code (refer to the above github issue for the workarounds). Then I created a very slim access-denied implementation in my JSS app. This is by no means production code and for starters, I guess that you at the very least should create a separate AccessDenied-component to handle this. But, if you just want to start by modifying your routehandler to handle 401-responses, you can use this as a simple reference.
In the state object initialization in the constructor of the RouteHandler class, add an accessDenied property:
In the updateRouteData function, add the else if section regarding 401 from the below snippet to the then() call from the getRouteData() call:
Add the below (or possibly, something more appropriate than this...) to the start of the render function:
Finally, somewhere down at the bottom of the file, add the below else if section regarding 401 to the getRouteData function:
02 Apr 2019, by Bonny Nilsson |
Sitecore 9.1, JSS, Layout service, Unauthorized, 401