Skip to content

Latest commit

 

History

History
327 lines (243 loc) · 18 KB

File metadata and controls

327 lines (243 loc) · 18 KB

The Resource Server

In this section we continue our discussion of how to use Spring Security with Angular JS in a "single page application". Here we start by breaking out the "greeting" resource that we are using as the dynamic content in our application into a separate server, first as an unprotected resource, and then protected by an opaque token. This is the third in a series of sections, and you can catch up on the basic building blocks of the application or build it from scratch by reading the first section, or you can just go straight to the source code in Github, which is in two parts: one where the resource is unprotected, and one where it is protected by a token.

Tip
if you are working through this section with the sample application, be sure to clear your browser cache of cookies and HTTP Basic credentials. In Chrome the best way to do that for a single server is to open a new incognito window.

A Separate Resource Server

Client Side Changes

On the client side there isn’t very much to do to move the resource to a different backend. Here’s the "home" controller in the last section:

hello.js
angular.module('hello', [ 'ngRoute' ])
...
.controller('home', function($http) {
    var self = this;
	$http.get('/resource/').then(function(response) {
		self.greeting = response.data;
	})
})
...

All we need to do to this is change the URL. For example, if we are going to run the new resource on localhost, it could look like this:

hello.js
angular.module('hello', [ 'ngRoute' ])
...
.controller('home', function($http) {
    var self = this;
	$http.get('http://localhost:9000/').then(function(response) {
		self.greeting = response.data;
	})
})
...

Server Side Changes

The UI server is trivial to change: we just need to remove the @RequestMapping for the greeting resource (it was "/resource"). Then we need to create a new resource server, which we can do like we did in the first section using the Spring Boot Initializr. E.g. using curl on a UN*X like system:

$ mkdir resource && cd resource
$ curl https://start.spring.io/starter.tgz -d style=web \
-d name=resource | tar -xzvf -

You can then import that project (it’s a normal Maven Java project by default) into your favourite IDE, or just work with the files and "mvn" on the command line.

Just add a @RequestMapping to the main application class, copying the implementation from the old UI:

ResourceApplication.java
@SpringBootApplication
@RestController
class ResourceApplication {

  @RequestMapping("/")
  public Message home() {
    return new Message("Hello World");
  }

  public static void main(String[] args) {
    SpringApplication.run(ResourceApplication.class, args);
  }

}

class Message {
  private String id = UUID.randomUUID().toString();
  private String content;
  public Message(String content) {
    this.content = content;
  }
  // ... getters and setters and default constructor
}

Once that is done your application will be loadable in a browser. On the command line you can do this

$ mvn spring-boot:run -Dserver.port=9000

and go to a browser at http://localhost:9000 and you should see JSON with a greeting. You can bake in the port change in application.properties (in"src/main/resources"):

application.properties
server.port: 9000

If you try loading that resource from the UI (on port 8080) in a browser, you will find that it doesn’t work because the browser won’t allow the XHR request.

CORS Negotiation

The browser tries to negotiate with our resource server to find out if it is allowed to access it according to the Cross Origin Resource Sharing protocol. It’s not an Angular JS responsibility, so just like the cookie contract it will work like this with all JavaScript in the browser. The two servers do not declare that they have a common origin, so the browser declines to send the request and the UI is broken.

To fix that we need to support the CORS protocol which involves a "pre-flight" OPTIONS request and some headers to list the allowed behaviour of the caller. Spring 4.2 has some nice fine-grained CORS support, so we can just add an annotation to our controller mapping, for example:

ResourceApplication.java
@RequestMapping("/")
@CrossOrigin(origins="*", maxAge=3600)
public Message home() {
  return new Message("Hello World");
}
Note
Blithely using origins=* is quick and dirty, and it works, but it is not not secure and is not in any way recommended.

Securing the Resource Server

Great! We have a working application with a new architecture. The only problem is that the resource server has no security.

Adding Spring Security

We can also look at how to add security to the resource server as a filter layer, like in the UI server. The first step is really easy: just add Spring Security to the classpath in the Maven POM:

pom.xml
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  ...
</dependencies>

Re-launch the resource server and, hey presto! It’s secure:

$ curl -v localhost:9000
< HTTP/1.1 302 Found
< Location: http://localhost:9000/login
...

We are getting a redirect to a (whitelabel) login page because curl is not sending the same headers that our Angular client will. Modifying the command to send more similar headers:

$ curl -v -H "Accept: application/json" \
    -H "X-Requested-With: XMLHttpRequest" localhost:9000
< HTTP/1.1 401 Unauthorized
...

So all we need to do is teach the client to send credentials with every request.

Token Authentication

The internet, and people’s Spring backend projects, are littered with custom token-based authentication solutions. Spring Security provides a barebones Filter implementation to get you started on your own (see for example AbstractPreAuthenticatedProcessingFilter and TokenService). There is no canonical implementation in Spring Security though, and one of the reasons why is probably that there’s an easier way.

Remember from Part II of this series that Spring Security uses the HttpSession to store authentication data by default. It doesn’t interact directly with the session though: there’s an abstraction layer (SecurityContextRepository) in between that you can use to change the storage backend. If we can point that repository, in our resource server, to a store with an authentication verified by our UI, then we have a way to share authentication between the two servers. The UI server already has such a store (the HttpSession), so if we can distribute that store and open it up to the resource server, we have most of a solution.

Spring Session

That part of the solution is pretty easy with Spring Session. All we need is a shared data store (Redis is supported out of the box), and a few lines of configuration in the servers to set up a Filter.

In the UI application we need to add some dependencies to our POM:

pom.xml
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

Spring Boot and Spring Session work together to connect to Redis and store session data centrally.

With that 1 line of code in place and a Redis server running on localhost you can run the UI application, login with some valid user credentials, and the session data (the authentication and CSRF token) will be stored in redis.

Tip
if you don’t have a redis server running locally you can easily spin one up with Docker (on Windows or MacOS this requires a VM). There is a docker-compose.yml file in the source code in Github which you can run really easily on the command line with docker-compose up. If you do this in a VM the Redis server will be running on a different host than localhost, so you either need to tunnel it onto localhost, or configure the app to point at the correct spring.redis.host in your application.properties.

Sending a Custom Token from the UI

The only missing piece is the transport mechanism for the key to the data in the store. The key is the HttpSession ID, so if we can get hold of that key in the UI client, we can send it as a custom header to the resource server. So the "home" controller would need to change so that it sends the header as part of the HTTP request for the greeting resource. For example:

hello.js
angular.module('hello', [ 'ngRoute' ])
...
.controller('home', function($http) {
  var self = this;
  $http.get('token').then(function(response) {
    $http({
      url : 'http://localhost:9000',
      method : 'GET',
      headers : {
        'X-Auth-Token' : response.data.token
      }
    }).then(function(response) {
      self.greeting = response.data;
    });
  })
});

(A more elegant solution might be to grab the token as needed, and use an Angular interceptor to add the header to every request to the resource server. The interceptor definition could then be abstracted instead of doing it all in one place and cluttering up the business logic.)

Instead of going directly to "http://localhost:9000" we have wrapped that call in the success callback of a call to a new custom endpoint on the UI server at "/token". The implementation of that is trivial:

UiApplication.java
@SpringBootApplication
@RestController
public class UiApplication {

  public static void main(String[] args) {
    SpringApplication.run(UiApplication.class, args);
  }

  ...

  @RequestMapping("/token")
  public Map<String,String> token(HttpSession session) {
    return Collections.singletonMap("token", session.getId());
  }

}

So the UI application is ready and will include the session ID in a header called "X-Auth-Token" for all calls to the backend.

Authentication in the Resource Server

There is one tiny change to the resource server for it to be able to accept the custom header. The CORS configuration has to nominate that header as an allowed one from remote clients, e.g.

ResourceApplication.java
@RequestMapping("/")
@CrossOrigin(origins = "*", maxAge = 3600,
    allowedHeaders={"x-auth-token", "x-requested-with"})
public Message home() {
  return new Message("Hello World");
}

The pre-flight check from the browser will now be handled by Spring MVC, but we need to tell Spring Security that it is allowed to let it through:

ResourceApplication.java
public class ResourceApplication extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
      .anyRequest().authenticated();
  }

  ...
Note
There is no need to permitAll() access to all resources, and there might be a handler that inadvertently sends sensitive data because it is not aware that the request is pre-flight. The cors() configuration utility mitigates this by handling all pre-flight requests in the filter layer.

All that remains is to pick up the custom token in the resource server and use it to authenticate our user. This turns out to be pretty straightforward because all we need to do is tell Spring Security where the session repository is, and where to look for the token (session ID) in an incoming request. First we need to add the Spring Session and Redis dependencies, and then we can set up the Filter:

ResourceApplication.java
@SpringBootApplication
@RestController
class ResourceApplication {

  ...

  @Bean
  HeaderHttpSessionStrategy sessionStrategy() {
    return new HeaderHttpSessionStrategy();
  }

}

This Filter created is the mirror image of the one in the UI server, so it establishes Redis as the session store. The only difference is that it uses a custom HttpSessionStrategy that looks in the header ("X-Auth-Token" by default) instead of the default (cookie named "JSESSIONID"). We also need to prevent the browser from popping up a dialog in an unauthenticated client - the app is secure but sends a 401 with WWW-Authenticate: Basic by default, so the browser responds with a dialog for username and password. There is more than one way to achieve this, but we already made Angular send an "X-Requested-With" header, so Spring Security handles it for us by default.

There is one final change to the resource server to make it work with our new authentication scheme. Spring Boot default security is stateless, and we want this to store authentication in the session, so we need to be explicit in application.yml (or application.properties):

application.yml
security:
  sessions: NEVER

This says to Spring Security "never create a session, but use one if it is there" (it will already be there because of the authentication in the UI).

Re-launch the resource server and open the UI up in a new browser window.

Why Doesn’t it All Work With Cookies?

We had to use a custom header and write code in the client to populate the header, which isn’t terribly complicated, but it seems to contradict the advice in Part II to use cookies and sessions wherever possible. The argument there was that not to do so introduces additional unecessary complexity, and for sure the implementation we have now is the most complex we have seen so far: the technical part of the solution far outweighs the business logic (which is admittedly tiny). This is definitely a fair criticism (and one we plan to address in the next section in this series), but let’s just briefly look at why it’s not as simple as just using cookies and sessions for everything.

At least we are still using the session, which makes sense because Spring Security and the Servlet container know how to do that with no effort on our part. But couldn’t we have continued to use cookies to transport the authentication token? It would have been nice, but there is a reason it wouldn’t work, and that is that the browser wouldn’t let us. You can just go poking around in the browser’s cookie store from a JavaScript client, but there are some restrictions, and for good reason. In particular you don’t have access to the cookies that were sent by the server as "HttpOnly" (which you will see is the case by default for session cookies). You also can’t set cookies in outgoing requests, so we couldn’t set a "SESSION" cookie (which is the Spring Session default cookie name), we had to use a custom "X-Session" header. Both these restrictions are for your own protection so malicious scripts cannot access your resources without proper authorization.

TL;DR the UI and resource servers do not have a common origin, so they cannot share cookies (even though we can use Spring Session to force them to share sessions).

Conclusion

We have duplicated the features of the application in Part II of this series: a home page with a greeting fetched from a remote backend, with login and logout links in a navigation bar. The difference is that the greeting comes from a resource server that is a standalone, instead of being embedded in the UI server. This added significant complexity to the implementation, but the good news is that we have a mostly configuration-based (and practically 100% declarative) solution. We could even make the solution 100% declarative by extracting all the new code into libraries (Spring configuration and Angular custom directives). We are going to defer that interesting task for after the next couple of installments. In the next section we are going to look at a different really great way to reduce all the complexity in the current implementation: the API Gateway Pattern (the client sends all its requests to one place and authentication is handled there).

Note
we used Spring Session here to share sessions between 2 servers that are not logically the same application. It’s a neat trick, and it isn’t possible with "regular" JEE distributed sessions.