I have a REST service using CXF, I have also placed an interceptor to check for basic authentication. When I am trying to access the REST service URL from browser, I did get an message thrown from Interceptor. But I was expecting a normal login popup.
REST service URL
http://localhost:8080/SpringRestBasicAuth/api/bookservice/books/1234
Error message on accessing the REST service URL:
<ns1:XMLFault xmlns:ns1="http://cxf.apache.org/bindings/xformat">
<ns1:faultstring xmlns:ns1="http://cxf.apache.org/bindings/xformat">java.lang.RuntimeException: 401 UNAUTHORIZED</ns1:faultstring>
</ns1:XMLFault>
CXF Servlet.XML
<jaxrs:server id="bookService" address="/bookservice">
<jaxrs:serviceBeans>
<ref bean="bs"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean='jsonProvider' />
</jaxrs:providers>
<jaxrs:inInterceptors>
<ref bean="logininterceptor" />
</jaxrs:inInterceptors>
</jaxrs:server>
<bean id="logininterceptor" class="org.gsdev.ws.bookservice.interceptor.AuthenticatorInterceptor"/>
AuthenticatorInterceptor class
public class AuthenticatorInterceptor extends AbstractPhaseInterceptor<Message> {
private Map<String,String> users;
public void setUsers(Map<String, String> users) {
this.users = users;
}
public AuthenticatorInterceptor() {
super(Phase.RECEIVE);
this.users = new HashMap<String, String>();
this.users.put("test", "test");
}
@Override
public void handleMessage(Message message) throws Fault {
AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
if (policy == null) {
System.out.println("User attempted to log in with no credentials");
throw new RuntimeException(HttpURLConnection.HTTP_UNAUTHORIZED+" UNAUTHORIZED");
}
System.out.println("Logging in use: " + policy.getUserName());
// Verify the password
String realPassword = users.get(policy.getUserName());
if (realPassword == null || !realPassword.equals(policy.getPassword())) {
System.out.println("Invalid username or password for user: " + policy.getUserName());
throw new RuntimeException(HttpURLConnection.HTTP_FORBIDDEN+" FORBIDDEN");
}
}
}
Can someone guide me so that when anyone tries to access the service URL then should get an normal login popup instead of direct exception message?
I think, you cannot send header login information from browser itself and you may need a tool like Postman to send the credentials. Or use any other client like Apache HTTPClient.