package ubic.gemma.web.services.rest.util;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.io.IOException;

public class RestAuthEntryPoint extends BasicAuthenticationEntryPoint {

    private static final String MESSAGE_401 = "Provided authentication credentials are invalid.";

    @Override
    public void commence( final HttpServletRequest request, final HttpServletResponse response,
            final AuthenticationException authException ) {

        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
        response.addHeader( "WWW-Authenticate", "Basic realm=" + getRealmName() + "" );
        response.setContentType( "application/json" );

        WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.UNAUTHORIZED, MESSAGE_401 );
        ResponseErrorObject errorObject = new ResponseErrorObject(errorBody);
        ObjectMapper mapperObj = new ObjectMapper();

        try {
            String jsonStr = mapperObj.writeValueAsString( errorObject );
            response.getWriter().println( jsonStr );
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() {
        setRealmName("Gemma rest api");
    }
}
@@ -568,16 +568,118 @@
 lid.%22;%0A%0A
+    @Override%0A    public void afterPropertiesSet() %7B%0A        setRealmName( %22Gemma rest api%22 );%0A    %7D%0A%0A
     @Ove
@@ -904,24 +904,108 @@
 THORIZED );%0A
+        // using 'xBasic' instead of 'basic' to prevent default browser login popup%0A
         resp
@@ -1041,16 +1041,17 @@
 cate%22, %22
+x
 Basic re
@@ -1317,16 +1317,17 @@
 rObject(
+ 
 errorBod
@@ -1327,16 +1327,17 @@
 rrorBody
+ 
 );%0A     
@@ -1614,106 +1614,6 @@
    %7D
-%0A%0A    @Override%0A    public void afterPropertiesSet() %7B%0A        setRealmName(%22Gemma rest api%22);%0A    %7D
 %0A%7D

Change authentication header of restapi service to prevent login popups