Wednesday, January 23, 2019

9. Role based data access

Many times we have a need to return data from an endpoint based on the role. Springframework provider easy mechanism for us to be able to do that. Let's take an example. In the previous example, we want to add a GET method in UserEndpoint that returns all the users. For any safe system, we want to return all the users if the role is ADMIN but if the role is USER then we want to return only that particular user. We don't want to write multiple methods for that purpose.
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @PostFilter("hasAuthority('ADMIN') or filterObject.authToken == authentication.name")
    public Iterable getUsers() {
        Iterable users = userRepository.findAll();
        return users;
    }
The method is described above. As we can see it is an extremely simple method, it calls findAll method on the repository which will return all the valid user records and returns an Iterable collection back. The interesting aspect of this method is in the @PostFilter annotation. Let's try to understand the annotation. The first condition is hasAuthority('ADMIN'). It implies that if the authenticated role is ADMIN then return the records as it is. The next bit of the filter condition uses an object called filterObject. This is an automatically defined expression that we can use in @PostAuthorize filter. A complete list of all the expressions exists here. The expression filterObject is used for each element of a collection that is returned from the endpoint. Since we know that when this endpoint is called, we would only be authenticating using authToken, the name of authentication in security context is set to the token itself. We can verify this in the code in AuthenticationFilter class.
            else {

                Optional token = getOptionalHeader(httpRequest,"token");
                TokenPrincipal authTokenPrincipal = new TokenPrincipal(token);
                processTokenAuthentication(authTokenPrincipal);
            }

The code fragment described above creates a TokenPrincipal object with the token as its name. That is the reason we have the condition filterObject.authToken == authentication.name. Taking the complete condition of @PostFilter we can see that the condition implies that return everything unconditionally if the role is ADMIN otherwise return the users with authToken as the currently authenticated user.
We have two users defined on the system. One has a role of the user and the other has a role of admin. Here are the examples of what happens when we call the endpoint with both of these users.
The first example is with a user with role USER.
$ curl -X GET "http://localhost:8081/user" -H "accept: application/json" -H "token: 3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631" | python -m json.tool
[
    {
        "authToken": "3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631",
        "email": "user@springframework.in",
        "expiry": 1548345909000,
        "fullname": "User",
        "id": 2,
        "mask": 1,
        "password": "User123",
        "username": "user"
    }
]

The second example is with a user with role ADMIN.
$ curl -X GET "http://localhost:8081/user" -H "accept: application/json" -H "token: a137dd09-11e4-4dcf-a141-0b235d39a505-60d43bf4-3674-4248-be1d-c2669f14589f" | python -m json.tool
[
    {
        "authToken": "3d47912d-73a0-4c4c-95e6-0486273d6221-28fa4f38-0f1b-4740-8e1d-3228288de631",
        "email": "user@springframework.in",
        "expiry": 1548345909000,
        "fullname": "User",
        "id": 2,
        "mask": 1,
        "password": "User123",
        "username": "user"
    },
    {
        "authToken": "a137dd09-11e4-4dcf-a141-0b235d39a505-60d43bf4-3674-4248-be1d-c2669f14589f",
        "email": "admin@springframework.in",                                                                                         
        "expiry": 1548348263000,                                                                                                     
        "fullname": "Administrator",                                                                                                 
        "id": 3,                                                                                                                     
        "mask": 4,                                                                                                                   
        "password": "Admin123",                                                                                                      
        "username": "admin"                                                                                                          
    }
]

As we can see above, the call with the role USER only returns the object related to that particular user while the call with the role returns all the users present in the system. This is how we can achieve role based object access without writing multiple endpoints.

Tuesday, January 22, 2019

8. That little matter of creating a user

Now that our simplified authentication system is in place, we are faced with the little matter of how to create a new user. Since we don't have a username, password, or token we can't really create a new user.
To accomplish that, we need to make some modifications to our AuthenticationFilter.  In the doFilter method, we add a special if block to take care of user creation.
            if (httpRequest.getRequestURI().toString().equals("/user") && httpRequest.getMethod().equals("POST")) {

                Optional username = getOptionalHeader(httpRequest,"username");
                UsernamePasswordPrincipal usernamePasswordPrincipal = new UsernamePasswordPrincipal(username, username, true);
                processUsernameAuthentication(usernamePasswordPrincipal);
            }
            else if (httpRequest.getRequestURI().toString().equals("/authenticate") && httpRequest.getMethod().equals("POST")) {

                Optional username = getOptionalHeader(httpRequest,"username");
                Optional password = getOptionalHeader(httpRequest,"password");
                UsernamePasswordPrincipal usernamePasswordPrincipal = new UsernamePasswordPrincipal(username, password);
                processUsernameAuthentication(usernamePasswordPrincipal);
            }

As we can see the code fragment, if the call is made to /user endpoint with POST method, we look for a username header and trigger spring authentication. We also need to make a change in the UsernamePasswordPrincipal to take a flag that would tell us if the user is a new user or existing user.
Now that we have modified the principal and filter, we need to handle this in the provider. The provider that gets invoked for username and password authentication is UsernamePasswordAuthenticationProvider.
As we can see in the provider's authenticate method, we have added an if block that checks if this is a new user. In case it is a new user, we authenticate this user with a role NEWUSER. The create user endpoint is only allowed to be called for a role NEWUSER.
Now that we have stitched the path for authentication of a new user to create user endpoint, we can see the endpoint itself.
    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize(MyConstants.ANNOTATION_ROLE_NEWUSER)
    public Optional createUser(@RequestHeader(value="username") String username, @RequestBody User user) {
        user.setMask(Role.USER.ordinal());
        User storedUser = userRepository.save(user);
        storedUser.setPassword(null);
        return Optional.of(storedUser);
    }
As we can see, we have a @PreAuthorize added with NEWUSER role. We also set the role of the user to the USER. Before returning the response, we set the password to null.
This fixes our service to allow the creation of a new user. The complete code is available tagged as v1.1 for this and previous posts.

7. Enabling Swagger

Before we proceed any further, let's enable swagger on our service so that testing it becomes easy. The first step is to add springfox dependencies.

Now that we have dependencies added, we need to define a swagger configuration. Most of our endpoint will need to have a token passed as HTTP header, we need to configure our swagger configuration to facilitate that.

We create a swagger configuration file as defined above. The globalOperationParameters clause dictates to swagger that each endpoint will have a parameter named token of type header and is mandatory. We know there is two endpoint that will not have a token header but we can just pass some dummy values. We can also make it non-mandatory if we so wish.

We also modify authentication endpoint to take a username and password header for authentication endpoint. That is defined in the AuthenticateEndpoint as above. Look at the @RequestHeader parameter passed in the login method of the endpoint.
        web.ignoring().antMatchers("/swagger-ui.html");
        web.ignoring().antMatchers("/v2/api-docs/**");
        web.ignoring().antMatchers("/swagger-resources/**");


Also, make sure that SecurityConfiguration.java that we had defined in one of the previous posts a list of swagger related URLs were made part of an exception list so that these do not go through authentication filter.
Now if we rebuild the server and run it and visit http://localhost:8081/swagger-ui.html we see the swagger page with all the API endpoints listed there. Here is the screenshot of the swagger UI as seen on visiting above URL.

Friday, January 4, 2019

6. Introducing Spring Security

If the web services that we are building require any level of authentication and authorization, it is better to understand Spring security context. Services that are properly built with security context can implement a better level of security at each method and endpoint level.
We want to handle all the security, authentication and, authorization related code in a single block so that managing it becomes easier.
The first step that we need to do is to add security dependencies in the pom.xml.
For authentication and authorization to make sense, we need to have a concept of a Role within the system. The roles are required to authorize the users for specific purposes. We define a set of roles in the form of a bitmask defined as an enum.

Now that we have defined Roles, we need to add few fields in our User class. We add a field mask for holding allowed roles and two different fields for authToken and expiry. We also add an index in the User entity.

We also need to add a class that implements GrantedAuthority interface. An authority in the spring security system is represented by a string and we use the Role enum name as the authority in the system.

We probably need to have two different types of authentication and authorization within the server. The first authentication and authorization will work with username and password and the second one will work with the token. Spring security requires two different entities to be defined for authentication and authorization. We need a Principal and a Provider class each for username and token authentication and authorization. Let's first look at the class required for authentication using username and password.  A principal is nothing but the abstraction of credentials that is flowing through spring security. We define it as below.

A provider is a class that provides the authentication and authorization functionality for a particular type. The username and password provider is defined as below. As we can see, the provider class extracts the credentials from the Principal and then makes sure the password is correct for the username. It also populates the list of roles granted to the user in the form of Authority.

Similarly, we define a Token principal. This principal just contains the token value that is received from the user.

We also define a token provider. The token provider looks up the user from the database by querying it from token and authenticates the user. In this example, we are making an implicit assumption that a token will be unique across all the users. If that were not to be the case, we will also have to pass the username or some other identifier for the user along with the token during authentication.

We also define a class RequestContext that will contain a set of thread local variables so that once authenticated, we will not need to look up the user details from the database. We will only need to hit the database in cases where we need to update the record in the User table.
We can see in both provider classes, after successful authentication of the user, the User is set into the thread local so that we can use it within the thread boundaries of that request.
Now the providers and principals are in place, we need to start using them. Rather than using them on a case to case basis, the best way is to define a filter which applies on each request and authentication and authorization can be done on all requests.

AuthenticationFilter provides the doFilter method which is called for each incoming request. As we can see within the doFilter method, if we receive a POST request to /authenticate URL we assume that to be a username and password authentication and we process it as a username and password authentication, in all other cases, it is assumed to be a token-based authentication. All the three parameters, username, password, and token are expected to be passed as headers.
Now we need to plug everything in so that it is called by the system. For that, we need to define a security configuration.
The SecurityConfiguration class is defined by extending WebSecurityConfigurerAdapter class. We override a few sets of methods. The first method defines a set of authentication providers that are available to the system.
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(tokenAuthenticationProvider());
        auth.authenticationProvider(usernamePasswordAuthenticationProvider());
    }

The second method defines a set of URLs that would be ignored by the security system.
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/manage/health");
        web.ignoring().antMatchers("/swagger-ui.html");
        web.ignoring().antMatchers("/webjars/**");
        web.ignoring().antMatchers("/v2/api-docs/**");
        web.ignoring().antMatchers("/error");
        web.ignoring().antMatchers("/swagger-resources/**");
    }

The third method defines the security rules for all the requests.
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().
                sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                and().
                authorizeRequests().
                antMatchers(actuatorEndpoints()).hasAuthority(Role.ADMIN.name()).
                anyRequest().authenticated().
                and().
                anonymous().disable().
                exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());;

        http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
    }

The configuration first disables CSRF and then sets a session management policy. After that, it declares that all the actuator endpoints need to be authenticated by a user having the ADMIN roles. Then all other users need to be authenticated. With this, every request coming into the system will be automatically authenticated and authorized. Now we can annotate our endpoints with specific roles so that unauthorized users can not make the calls. For example, we add the following annotation to our endpoint that we had defined earlier.
@PreAuthorize("hasAuthority('USER')")

This annotation implies that a user with the role of USER can only call this endpoint. Any other user would not be able to call this endpoint.

This is also our AuthenticationEndpoint. This will need to be called when a user wants to login using username and password. This now provides us with a functioning service with spring security enabled. In future posts, we will provide more details on it.  The complete code for this post is available in github repository with version 1.0. Click here to download it.