Saturday, April 23, 2016

How to create a client for 'X-Auth-Token' authentication over Spring Security implementation on a Rest Service?

I am building an application for practicing an architecture and its balance, I have to create a client for testing purpose, the rest service use tokens for authentication implementing Spring Security that employs: authentication-manager, security http, AuthenticationTokenProcessingFilter, intercept-url and tokens, so after some reading I have to resolve 'X-Auth-Token' inject on headers and authentication part, the following lines are for testing this king of Authentication:

package org.osanchezh.keepnotes.soa.app.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.osanchezh.keepnotes.soa.integration.transfer.TokenTransfer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
public class SecurityNewsEntryRestTest {
public static final String URL = "http://localhost:8081/my-app/rest/news";
public static final String URL_SECURITY = "http://localhost:8081/my-app/rest/user/authenticate";
private static final Logger LOGGER = LoggerFactory.getLogger(SecurityNewsEntryRestTest.class);
@Test
public void testLoginRestService(){
try{
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", "admin");
map.add("password", "admin");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
TokenTransfer tokenTransfer = restTemplate.postForObject(URL_SECURITY, request, TokenTransfer.class);
String token1=tokenTransfer.getToken();
LOGGER.debug("token="+token1);
RestTemplate restTemplate1 = new RestTemplate();
HttpHeaders headers1= new HttpHeaders();
headers1.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers1.add("X-Auth-Token", token1);
HttpEntity<String> entity1 = new HttpEntity<String>("request", headers1);
ResponseEntity<String> result1 = restTemplate1.exchange(URL, HttpMethod.GET, entity1 ,String.class);
LOGGER.debug("RESULTADO="+result1.getBody());
}catch(ResourceAccessException ex){
LOGGER.error(ex.getMessage(),ex);
}
}
}
}
By now we have a client for test authentication and authorization for next steps.

Best regards,

How to resolve CORS header after using Spring Security and Rest Service?


After testing an architecture of a security rest service built-in Spring Framework and a web application on AngularJS which over a POST gets credentials and regard information for the front end part, using firebug I discover and error after a submit on each event:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/keepnotes-soa-app/rest/user. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Reviewing on Internet I discovered a missing configuration over my Front-end application which is the result of having a separated application, so on I have to create the following lines:
package org.app.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
LOGGER.debug("FILTO.CORS.INIT.0");
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOGGER.debug("FILTO.CORS.INIT.1");
LOGGER.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Auth-Token");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
view raw CORSFilter.java hosted with ❤ by GitHub
Having created the filter class we must to make the configuration over web.xml with the following lines:

...
<filter>
<filter-name>cors</filter-name>
<filter-class>org.app.web.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
view raw cors_web.xml hosted with ❤ by GitHub
Next to is review request and response where you were to find headers located on each message.

Best Regards,

Wednesday, April 6, 2016

How to solve 'ANDROID_SDK_ROOT is undefined'?

After a brief reading over Internet using Android Studio 1.5 default installation, I have named several issues, one of them is the use of API 23 or Android 6 because of demo version the components are not well suited, several of the problems are solved executing ./android in the folder ~/Android/sdk/tools ,install the recommend SDK's like API 18 or below...

Try avd monitor we have following errors like:

emulator: ERROR: This AVD's configuration is missing a kernel file!!
emulator: ERROR: ANDROID_SDK_ROOT is undefined

The solution is to soaring ./android again and install sources of each API installed.