Wednesday, 8 January 2014

Accessing Spring Secured URL with Java ImageIo.read()

Problem Statement: Accessing Spring Secured URL with Java ImageIo.read()
There is a requirement in my application, where i need to access the spring secured URL using ImageIO.read(urlConnection.getInputStream()) of Java.

But the problem was, it always resulted in non authorized and i was redirected to the login page.
So ImageIO.read(urlConnection.getInputStream()) gives null always.

Solution:
After a long search i found the spring's Delegatingauthenticationentrypoint could be the easiest and simple solution.

So the approach which i followed is,

In Java client where you want to read the image,

First,Create Basic authentication String and set that in connection
String authString = SecurityContextHolder.getContext().getAuthentication().getName() + ":" + SecurityContextHolder.getContext().getAuthentication().getCredentials().toString();
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

Then use ImageIo.read() as follows,
image = ImageIO.read(urlConnection.getInputStream());

In Springsecurity.xml,

Add these below statements
<security:http auto-config="false" use-expressions="true"
entry-point-ref="authenticationEntryPoint">
<security:custom-filter position="FORM_LOGIN_FILTER" ref="myFilter" />
<security:custom-filter ref="basicAuthenticationFilter" after="BASIC_AUTH_FILTER" />
</security:http>

Now define authenticationEntryPoint,
<bean id="authenticationEntryPoint"
class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">              <constructor-arg>
<map>
<entry key="hasHeader('User-Agent','Java')"
value-ref="basicAuthEntryPoint" />
</map>
</constructor-arg>
<property name="defaultEntryPoint" ref="LoginUrlAuthenticationEntryPoint"/>
</bean>

This clearly tells that, requests which all has headers with User-Agent as Java will use the
basicAuthEntryPoint.
And whichever fails that condition they will use the LoginUrlAuthenticationEntryPoint.

No comments:

Post a Comment