HOW-TO: Get started quickly with Spring 4.0 to build a simple REST-Like API (walkthrough)
Yet another tutorial about creating Web API with Spring MVC. Not really sophisticated. Just a walkthrough. The resulting app will serve simple API, will use Mongo as its persistence and it will be secured with Spring Security.
Getting started – POM
Of course, I am still a huge fan of Maven so the project is Maven based. Since there is Spring 4.0 RC2 available, I decided to utilize its new dependency managament which results in the following pom.xml: It is quite simple as it goes to Spring MVC application. The new thing is thedependencyManagement
element. More explanation on that can be found here: http://spring.io/blog/2013/12/03/spring-framework-4-0-rc2-available
Configuration
The application is configured using JavaConfig. I divided it into several parts:
ServicesConfig
02 |
public class ServicesConfig { |
05 |
private AccountRepository accountRepository; |
08 |
public UserService userService() { |
09 |
return new UserService(accountRepository); |
13 |
public PasswordEncoder passwordEncoder() { |
14 |
return NoOpPasswordEncoder.getInstance(); |
No component scan. Really simple.
PersistenceConfig
A MongoDB configuration with all available repositories. In this simple application we have only one repository, so the configuration is really simple.
02 |
class PersistenceConfig { |
05 |
public AccountRepository accountRepository() throws UnknownHostException { |
06 |
return new MongoAccountRepository(mongoTemplate()); |
10 |
public MongoDbFactory mongoDbFactory() throws UnknownHostException { |
11 |
return new SimpleMongoDbFactory( new Mongo(), "r" ); |
15 |
public MongoTemplate mongoTemplate() throws UnknownHostException { |
16 |
MongoTemplate template = new MongoTemplate(mongoDbFactory(), mongoConverter()); |
21 |
public MongoTypeMapper mongoTypeMapper() { |
22 |
return new DefaultMongoTypeMapper( null ); |
26 |
public MongoMappingContext mongoMappingContext() { |
27 |
return new MongoMappingContext(); |
31 |
public MappingMongoConverter mongoConverter() throws UnknownHostException { |
32 |
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), mongoMappingContext()); |
33 |
converter.setTypeMapper(mongoTypeMapper()); |
SecurityConfig
In theory, Spring Security 3.2 can be fully configured with JavaConfig. For me it is still a theory, so I use XML here:
2 |
@ImportResource ( "classpath:spring-security-context.xml" ) |
3 |
public class SecurityConfig {} |
And the XML: As you can see basic authentication will be used for the API.
WebAppInitializer
We don’t want the web.xml so we use the following code to configure the web application:
02 |
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { |
05 |
protected String[] getServletMappings() { |
06 |
return new String[]{ "/" }; |
10 |
protected Class[] getRootConfigClasses() { |
11 |
return new Class[] {ServicesConfig. class , PersistenceConfig. class , SecurityConfig. class }; |
15 |
protected Class[] getServletConfigClasses() { |
16 |
return new Class[] {WebMvcConfig. class }; |
20 |
protected Filter[] getServletFilters() { |
21 |
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); |
22 |
characterEncodingFilter.setEncoding( "UTF-8" ); |
23 |
characterEncodingFilter.setForceEncoding( true ); |
24 |
return new Filter[] {characterEncodingFilter}; |
28 |
protected void customizeRegistration(ServletRegistration.Dynamic registration) { |
29 |
registration.setInitParameter( "spring.profiles.active" , "default" ); |
WebAppSecurityInitializer
New to Spring Security 3.
2 |
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer { |
WebMvcConfig
The dispatcher servlet configuration. Really basic. Only crucial components to build a simple API.
02 |
@ComponentScan (basePackages = { "pl.codeleak.r" }, includeFilters = { @Filter (value = Controller. class )}) |
03 |
public class WebMvcConfig extends WebMvcConfigurationSupport { |
05 |
private static final String MESSAGE_SOURCE = "/WEB-INF/i18n/messages" ; |
08 |
public RequestMappingHandlerMapping requestMappingHandlerMapping() { |
09 |
RequestMappingHandlerMapping requestMappingHandlerMapping = super .requestMappingHandlerMapping(); |
10 |
requestMappingHandlerMapping.setUseSuffixPatternMatch( false ); |
11 |
requestMappingHandlerMapping.setUseTrailingSlashMatch( false ); |
12 |
return requestMappingHandlerMapping; |
15 |
@Bean (name = "messageSource" ) |
16 |
public MessageSource messageSource() { |
17 |
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); |
18 |
messageSource.setBasename(MESSAGE_SOURCE); |
19 |
messageSource.setCacheSeconds( 5 ); |
24 |
public Validator getValidator() { |
25 |
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); |
26 |
validator.setValidationMessageSource(messageSource()); |
31 |
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { |
And that’s the config. Simple.
IndexController
To verify the config is fine, I created an IndexController, that serves simple “Hello, World” like text:
03 |
public class IndexController { |
07 |
public String index() { |
08 |
return "This is an API endpoint." ; |
As you run the application, you should see this text in the browser.
Building the API
UserService
To finish up with the Spring Security configuration, one part is actually still needed: UserService which instance was created earlier:
01 |
public class UserService implements UserDetailsService { |
03 |
private AccountRepository accountRepository; |
05 |
public UserService(AccountRepository accountRepository) { |
06 |
this .accountRepository = accountRepository; |
10 |
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { |
11 |
Account account = accountRepository.findByEmail(username); |
13 |
throw new UsernameNotFoundException( "user not found" ); |
15 |
return createUser(account); |
18 |
public void signin(Account account) { |
19 |
SecurityContextHolder.getContext().setAuthentication(authenticate(account)); |
22 |
private Authentication authenticate(Account account) { |
23 |
return new UsernamePasswordAuthenticationToken(createUser(account), null , Collections.singleton(createAuthority(account))); |
26 |
private User createUser(Account account) { |
27 |
return new User(account.getEmail(), account.getPassword(), Collections.singleton(createAuthority(account))); |
30 |
private GrantedAuthority createAuthority(Account account) { |
31 |
return new SimpleGrantedAuthority(account.getRole()); |
The requirement was to build an API endpoint that handles 3 methods: gets currently logged in user, gets all users (not really safe), creates a new account. So let’s do it.
Account
Account will be our first Mongo document. It is really easy one:
01 |
@SuppressWarnings ( "serial" ) |
03 |
public class Account implements java.io.Serializable { |
06 |
private String objectId; |
09 |
@Indexed (unique = true ) |
14 |
private String password; |
16 |
private String role = "ROLE_USER" ; |
22 |
public Account(String email, String password, String role) { |
24 |
this .password = password; |
Repository
I started with the interface:
1 |
public interface AccountRepository { |
3 |
Account save(Account account); |
7 |
Account findByEmail(String email); |
And later with its Mongo implementation:
01 |
public class MongoAccountRepository implements AccountRepository { |
03 |
private MongoTemplate mongoTemplate; |
05 |
public MongoAccountRepository(MongoTemplate mongoTemplate) { |
06 |
this .mongoTemplate = mongoTemplate; |
10 |
public Account save(Account account) { |
11 |
mongoTemplate.save(account); |
16 |
public List findAll() { |
17 |
return mongoTemplate.findAll(Account. class ); |
21 |
public Account findByEmail(String email) { |
22 |
return mongoTemplate.findOne(Query.query(Criteria.where( "email" ).is(email)), Account. class ); |
API Controller
So we are almost there. We need to serve the content to the user. So let’s create our endpoint:
02 |
@RequestMapping ( "api/account" ) |
03 |
class AccountController { |
05 |
private AccountRepository accountRepository; |
08 |
public AccountController(AccountRepository accountRepository) { |
09 |
this .accountRepository = accountRepository; |
12 |
@RequestMapping (value = "current" , method = RequestMethod.GET) |
13 |
@ResponseStatus (value = HttpStatus.OK) |
15 |
@PreAuthorize (value = "isAuthenticated()" ) |
16 |
public Account current(Principal principal) { |
17 |
Assert.notNull(principal); |
18 |
return accountRepository.findByEmail(principal.getName()); |
21 |
@RequestMapping (method = RequestMethod.GET) |
22 |
@ResponseStatus (value = HttpStatus.OK) |
24 |
@PreAuthorize (value = "isAuthenticated()" ) |
25 |
public Accounts list() { |
26 |
List accounts = accountRepository.findAll(); |
27 |
return new Accounts(accounts); |
30 |
@RequestMapping (method = RequestMethod.POST) |
31 |
@ResponseStatus (value = HttpStatus.CREATED) |
33 |
@PreAuthorize (value = "permitAll()" ) |
34 |
public Account create( @Valid Account account) { |
35 |
accountRepository.save(account); |
39 |
private class Accounts extends ArrayList { |
40 |
public Accounts(List accounts) { |
I hope you noticed that we talk directly to the repository, so the passwords will not be encoded. Small detail to be fixed later on, if you wish. For now it is OK.
Finishing up
The last think I needed was some error handler so the consumer can see error messages in JSON instead of HTML. This is simple with Spring MVC and @Controller advice.
02 |
public class ErrorHandler { |
04 |
@ExceptionHandler (value = Exception. class ) |
05 |
@ResponseStatus (HttpStatus.BAD_REQUEST) |
07 |
public ErrorResponse errorResponse(Exception exception) { |
08 |
return new ErrorResponse(exception.getMessage()); |
13 |
public class ErrorResponse { |