Developing a web API with SPRING and ANGULAR.JS (Part 2)

In part 1 we set up the Spring project for our backend. In this part we will add some functionality to our API.

First we will define a model User which will be used for authorization, and our API will work with these Users. But more on that later. Let’s start with the User and authorization.

As we can see we have a basic User model. However we annotated some of the members with  @JsonView(Views.Public.class) which is later used by methods in the API to filter what information should be added to the JSON return object. This is part of the Jaxon integration to Spring. For this to work we need another class:

Ok, up until now we have not done anything interesting. But it’s about to change. Let’s have a look at our CustomUserDetailsService:

So what are we doing here? In  loadUserByUsername(String s)  we load the user from the userservice. The userservice could then load the user from the actual database or some other resource which we will not inspect any closer. For the moment we will just expect the userservice to do what is expected of it.  We then wrap our own user in a CustomUserDetails which extends our custom User model with Springs UserDetails . Since we only need the CustomUserDetails inside of this service, we define it within this class.  First we have a copy constructor for the CustomUserDetails , which takes all the information from the passed user and copies in to the current instance of CustomUserDetails. We then define a view methods required by UserDetails, of which only getAuthorities() is of any interest. It wraps our Role Strings in SimpleGrantedAuthority classes which is later required for  security annotations.

So now let’s get some actual work done. We will start by creating a RestController which will provide us with some access point for our API.

The UserController provides a list of users at the url  “/api/search/users/all”. When we navigate to this URL we will be first redirected to /login where we can login using credentials of a user provided by userservice. After successful login, we should be taken to the original URL where we will see a JSON object containing all Users with their data filtered by all members annotated with @JsonView(Views.Public.class). The Login page is provided by Spring, since we did not provide our own login form (Spring is really neat sometimesJ). We have a TODO in our code telling us that we still need method security annotations here, but we will cover this at a later stage. For now we are happy that this resource is accessible by all logged in users.

In part 3 we will finally start working on the frontend using Angular.JS and querying our API with AJAX requests.

Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


3 × five =