Technology stack growing pains

The basic technology stack of the funnel.travel server and web client is pretty much defined. The server will be running on a Java app server, the code is based on the Spring framework, jOOQ and an underlying PostgreSQL DBMS. Mainstream stuff, really. The client will be a stand-alone Angular 4 client, with Material design. A tad unexpected are the basic issues of getting a simple login to work.

CORS

Cross-origin resource sharing becomes an issue when separating the server part from the web client. In a traditional Java stack, the entire application would be served (locally) on localhost:8080. But now, the server is running on localhost:8080, while the ng client is on localhost:4200.

The key point is to enable CORS on the WebSecurityConfigurerAdapter subclass

@Override
protected void configure(final HttpSecurity http) throws Exception {
   ...
   http.cors().configurationSource(corsConfigurationSource())
   ...
}

Make sure the CorsConfiguration allows the OPTIONS method, as NG uses that as a pre-flight check on cross-origin HTTP requests.

CSRF

Once the OPTIONS request is processed ok, the next issue is “Could not verify the provided CSRF token because your session was not found.”. A surprising number of Stackoverflow answers will suggest to simply disable Cross-site request forgery checks in Spring. But we’re developing a brand-new application, and disregarding CSRF seems like the wrong approach. (If you’re already going: “But you don’t …”, maybe skip this chapter. I’m leaving it in to illustrate the learning curve.)

A first step is to tell Spring to use a cookie-based repository instead of the default HTTP session one. The cookie name ‘XSRF-TOKEN’ is exactly what Angular is looking for.

@Override
protected void configure(final HttpSecurity http) throws Exception {
    ...
    http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    ...
}

The client-side counterpart in Angular is enabled by default, but if you’re curious google for “CookieXSRFStrategy”. Now all that is needed is to initially get a XSRF token, and then Angular will pass that on as HTTP header in subsequent requests.

Except, this doesn’t yet work because the XHR are cross-origin. First we need to update our Spring configuration

CorsConfiguration#setAllowCredentials(true)

and in Angular set

let options = new RequestOptions();
options.withCredentials = true;

to make the cross-origin HTTP requests aware of cookies (more here). The issue now is that the Angular CookieXSRFStrategy would need to read and store the XSRF cookie from the API domain, in order to set it as “X-XSRF-TOKEN” header. As the cookie is from cross-origin, Angular doesn’t have access to the cookie.

Now that the issue is to handle CSRF on cross-origin, the penny finally drops. What CSRF does is to prevent the server from regarding a request as valid based only on cookies. The approach is to require a specific HTTP header, with a value that is dynamic and verifiable on the server (thus some form of token).

Note on the side: I’ve read statements like “If your server requires a HTTP header “X-Requested-With: XMLHttpRequest” you’re already safe, because a browser will never send that header.” I disagree there, because an attacker can easily create CSRF attack using an ajax framework.

We’re planning to use OAuth2 to handle authentication, which means that our client will be sending an “Authorization: Bearer” header with every request. Here’s the HTTP header which will prevent CSRF! I’m disabling CSRF on Spring now…

@Override
protected void configure(final HttpSecurity http) throws Exception {
    ...
    http.csrf().disable()
    ... 
}

 

Login mechanism / OAuth2

(Whenever this blog mentions ‘OAuth’, we’re refering to ‘OAuth2’).

We’re heading for a token-based authentication (great post from Chris Sevilleja), in part for scalability, but also because we anticipate future clients accessing our API (both interactive and machine clients). OAuth2 seems like a natural choice (we discarded Firebase because funnel.travel will have an “all data is stored in Switzerland” option)

After getting a basic setup following tutorial like this one, the first issue is that the NG “OPTIONS” call is not authorized on /oauth/token. Spring seems to have some issues with CORS and OPTIONS calls, the main one that the Spring CORS filter is placed too late in the filter chain, such that security is applied first. As the OPTIONS call will never have an ‘Authorized’ header, it will be rejected. For now we’re using the hack described on this stackoverflow post.

While the Angular web client can technically be seen as an “application accessing server resources on behalf of a user”, the user experience of a login resulting in a OAuth2 access pop up along the lines of “funnel.travel web client is asking for permission to access funnel.travel server. Do you want to grant permission?” wouldn’t be great. So, for our Angular client we want to support the Password Credentials grant flow.

Spring’s TokenEndpoint is a bit messed up when it comes to that grant flow, because the TokenEndpoint implementation expects an authenticated principal going into the postAccessToken() method. In Authorization Code or Implicit flow, this is fine as we’d be sending the client id + secret along. But for Password Credentials, the RFC 6749 allows for a flow without providing client id + secret.

Our approach is to add a TokenEndpointAuthenticationFilter which checks if the request is a grant_type=password request from a trusted origin. There’s some additional security by obscurity, but eventually leads to adding a client authentication. From there, the TokenEndpoint will issue a valid token.

@Override 
public void configure(final AuthorizationServerSecurityConfigurer oauthServerSecurityConfig) throws Exception {
    oauthServerSecurityConfig
            .addTokenEndpointAuthenticationFilter(new PasswordGrantAuthenticationFilter(environmentProperties.getAllowedCors()));
}

One weird effect we observed: when configuring basic web security, OAuth authorization server, OAuth resource server and finally OAuth method security in separate public classes, the resulting filter chain didn’t contain our custom filter mentioned above. Moving everything into one public class (with inner static classes) automagically resolved the issue.

Where are we now, what’s next?

Developer: We have an up and running Spring + Angular stack, CORS-enabled and secured with Spring Security and OAuth2, backed by jOOQ and PostgreSQL.

Sales guy: What, after all that time all you’ve got is a login page?

Up next: looking into i18n / l10n for Angular, which at first glance seems like rather over-engineered. But this is coming from server-side thinking of .

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s