Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring security error handling with JSON response

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.

like image 406
Zemzela Avatar asked Oct 21 '22 03:10

Zemzela


1 Answers

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
                }
            }
like image 71
shazinltc Avatar answered Oct 24 '22 03:10

shazinltc