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
[sourcecode language=”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;
}
}
[/sourcecode]
Now create security config class.
[sourcecode language=”java”]
@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
}
}
[/sourcecode]
Now add bean to MvcConfig class.
[sourcecode language=”java”]
@Bean
public MyBasicAuthenticationEntryPoint myBasicAuthenticationEntryPoint()
{
return new MyBasicAuthenticationEntryPoint();
}
[/sourcecode]
Then add SecurityConfig class to WebAppInitializer.
[sourcecode language=”java”]
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] {SecurityConfig.class };
}
}
[/sourcecode]
Then add
[sourcecode language=”java”]
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{
}
[/sourcecode]
Now create entry point.
[sourcecode language=”java”]
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();
}
}
[/sourcecode]
Now redirect to http:localhost/example/api/foo URL will request your credentials.