I'm using spring security 3.1 and Spring 3.2 for REST services. I'm struggling to make every response be JSON e.g. if user tries to access some resource but is not yet authenticated. Also if user make wrong request I want to return JSON with error message.
Just to mention that would be more acceptible to have some global place where I should catch all errors/exceptions.
why don't you write a controller class extended by all other controllers (or use @ControllerAdvice in case you are using 3.2) and include an exceptionhandler annotated method in that class? SOmething like this
@ExceptionHandler(Throwable.class)
public @ResponseBody GenericResponse handleException(Throwable throwable){
//handle exception
}
Or read this blog post
UPDATE
Sorry for this late reply. Here is my suggestion. Make it simply fail with a 403 response. For that just add the following snippet in your spring security configuration.
<beans:bean id="entryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
and point entrypoint-ref to this bean
<http auto-config="true" use-expressions="true" entry-point-ref="entryPoint">
And in the client side, in your AJAX code, add an error block
error : function( jqXHR, textStatus, errorThrown ){
if (jqXHR.status == 403){
alert('you need to login to do this operation');
window.location.href = contextPath+"/signin";
// or whatever you want to
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With