Spring Security : Basic Http Authentication

Suppose we need to create an API which requires user authentication to access that. Spring security is there to implement this on the fly.

First create your REST service

Service.java


@RestController
@RequestMapping("/api")
public class Service
{
private static final Logger LOGGER = LoggerFactory.getLogger( Service.class );

/**
* Clear the template cache
*
* @return response object with status and message
*/
@ResponseBody
@RequestMapping(value = "/foo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> accessApi()
{
Response<String> returnResponse = null;
try
{

returnResponse = new Response<String>( "", "Successfull", Response.SUCCESS );
}
catch ( Exception )
{
// TODO: handle exception
returnResponse = new Response<String>( "", "Error", Response.ERROR );
LOGGER.error( ex.getMessage() );
}

return returnResponse;
}

}

Now create security config class.


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

@Autowired
MyBasicAuthenticationEntryPoint myBasicAuthenticationEntryPoint;

@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception
{
auth.inMemoryAuthentication().withUser( "user" ) // #1
.password( "password" ).roles( "USER" );
}

@Override
protected void configure( HttpSecurity http ) throws Exception
{
// @formatter:off
http
.authorizeRequests()
.antMatchers("/api/foo").hasRole("USER")
.anyRequest().permitAll()
.and()
.httpBasic()
.authenticationEntryPoint( myBasicAuthenticationEntryPoint );
// @formatter:on
}

}

Now add bean to MvcConfig class.


@Bean
public MyBasicAuthenticationEntryPoint myBasicAuthenticationEntryPoint()
{
return new MyBasicAuthenticationEntryPoint();
}

Then add SecurityConfig class to WebAppInitializer.


public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] {SecurityConfig.class };
}

}

Then add


public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{

}

Now create entry point.


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint
{

@Override
public void commence( final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException ) throws IOException, ServletException
{
response.setHeader( "Access-Control-Allow-Origin", "*" );
response.setHeader( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE" );
response.setHeader( "Access-Control-Max-Age", "3600" );
response.setHeader( "Access-Control-Allow-Headers", "x-requested-with" );

response.addHeader( "WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"" );
response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
final PrintWriter writer = response.getWriter();
writer.println( "HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage() );
}

@Override
public void afterPropertiesSet() throws Exception
{
setRealmName( "FooService" );
super.afterPropertiesSet();
}
}

Now redirect to http:localhost/example/api/foo URL will request your credentials.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s