Spring Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE
Security Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll provide an overview of Spring Security Kerberos.

We'll write a Kerberos client in Java that authorizes itself to access our Kerberized service. And we'll run our own embedded Key Distribution Center to perform full, end-to-end Kerberos authentication. All that, without any external infrastructure required thanks to Spring Security Kerberos.

2. Kerberos and Its Benefits

Kerberos is a network authentication protocol that MIT created in the 1980s, specifically useful for centralizing authentication on a network.

In 1987, MIT released it to the Open Source community and it's still under active development. In 2005, it was canonized as an IETF standard under RFC 4120.

Usually, Kerberos is used in corporate environments.  In there, it secures the environment in such a way that the user doesn't have to authenticate to each service separately. This architectural solution is known as Single Sign-on.

Simply put, Kerberos is a ticketing system. A user authenticates once and receives a Ticket-granting Ticket (TGT). Then, the network infrastructure exchanges that TGT for Service Tickets. These service tickets allow the user to interact with infrastructure services, so long as the TGT is valid, which is usually for a couple of hours.

So, it's great that the user only signs in one time. But there's a security benefit, too: In such an environment, the user's password is never sent over the network. Instead, Kerberos uses it as a factor to generate another secret key that's gonna be used to message encryption and decryption.

Another benefit is that we can manage users from a central place, say one that's backed by LDAP. Therefore, if we disable an account in our centralized database for a given user, then we'll revoke his access in our infrastructure. Thus, the administrators don't have to revoke the access separately in each service.

3. Kerberized Environment

So, let's create an environment for authenticating with the Kerberos protocol. The environment will consist of three separate applications that will run simultaneously.

First, we'll have a Key Distribution Center that will act as the authentication point. Next, we'll write a Client and a Service Application that we'll configure to use Kerberos protocol.

Now, running Kerberos requires a bit of installation and configuration. However, we'll leverage Spring Security Kerberos, so we'll run the Key Distribution Center programmatically, in embedded mode. Also, the MiniKdc shown below is useful in case of integration testing with Kerberized infrastructure.

3.1. Running a Key Distribution Center

First, we'll launch our Key Distribution Center, that will issue the TGTs for us:

String[] config = MiniKdcConfigBuilder.builder()
  .workDir(prepareWorkDir())
  .principals("client/localhost", "HTTP/localhost")
  .confDir("minikdc-krb5.conf")
  .keytabName("example.keytab")
  .build();

MiniKdc.main(config);

Basically, we've given MiniKdc a set of principals and a configuration file; additionally, we've told MiniKdc what to call the keytab it generates.

MiniKdc will generate a krb5.conf file that we'll supply to our client and service applications. This file contains the information where to find our KDC – the host and port for a given realm.

MiniKdc.main starts the KDC and should output something like:

Standalone MiniKdc Running
---------------------------------------------------
  Realm           : EXAMPLE.COM
  Running at      : localhost:localhost
  krb5conf        : .\spring-security-sso\spring-security-sso-kerberos\krb-test-workdir\krb5.conf

  created keytab  : .\spring-security-sso\spring-security-sso-kerberos\krb-test-workdir\example.keytab
  with principals : [client/localhost, HTTP/localhost]

3.2. Client Application

Our client will be a Spring Boot application that's using a RestTemplate to make calls to external a REST API.

But, we're going to use KerberosRestTemplate instead. It'll need the keytab and the client's principal:

@Configuration
public class KerberosConfig {

    @Value("${app.user-principal:client/localhost}")
    private String principal;

    @Value("${app.keytab-location}")
    private String keytabLocation;

    @Bean
    public RestTemplate restTemplate() {
        return new KerberosRestTemplate(keytabLocation, principal);
    }
}

And that's it! KerberosRestTemplate negotiates the client side of the Kerberos protocol for us.

So, let's create a quick class that will query some data from a Kerberized service, hosted at the endpoint app.access-url:

@Service
class SampleClient {

    @Value("${app.access-url}")
    private String endpoint;

    private RestTemplate restTemplate;

    // constructor, getter, setter

    String getData() {
        return restTemplate.getForObject(endpoint, String.class);
    }
}

So, let's create our Service Application now so that this class has something to call!

3.3. Service Application

We'll use Spring Security, configuring it with the appropriate Kerberos-specific beans.

Also, note that the service will have its principal and use the keytab, too:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${app.service-principal:HTTP/localhost}")
    private String servicePrincipal;

    @Value("${app.keytab-location}")
    private String keytabLocation;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and() 
          .exceptionHandling()
            .authenticationEntryPoint(spnegoEntryPoint())
            .and()
          .formLogin()
            .loginPage("/login").permitAll()
            .and()
          .logout().permitAll()
            .and()
          .addFilterBefore(spnegoAuthenticationProcessingFilter(authenticationManagerBean()),
            BasicAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .authenticationProvider(kerberosAuthenticationProvider())
          .authenticationProvider(kerberosServiceAuthenticationProvider());
    }

    @Bean
    public KerberosAuthenticationProvider kerberosAuthenticationProvider() {
        KerberosAuthenticationProvider provider = new KerberosAuthenticationProvider();
        // provider configuration
        return provider;
    }

    @Bean
    public SpnegoEntryPoint spnegoEntryPoint() {
        return new SpnegoEntryPoint("/login");
    }

    @Bean
    public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(
      AuthenticationManager authenticationManager) {
        SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter();
        // filter configuration
        return filter;
    }

    @Bean
    public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() {
        KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider();
        // auth provider configuration  
        return provider;
    }

    @Bean
    public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
        SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
        // validator configuration
        return ticketValidator;
    }
}

Note that we've configured Spring Security for SPNEGO authentication. This way, we'll be able to authenticate through the HTTP protocol, though we can also achieve SPNEGO authentication with core Java.

4. Testing

Now, we'll run an integration test to show that our client successfully retrieves data from an external server over the Kerberos protocol. To run this test, we need to have our infrastructure running, so MiniKdc and our Service Application both must be started.

Basically, we'll use our SampleClient from the Client Application to make a request to our Service Application. Let's test it out:

@Autowired
private SampleClient sampleClient;

@Test
public void givenKerberizedRestTemplate_whenServiceCall_thenSuccess() {
    assertEquals("data from kerberized server", sampleClient.getData());
}

Note that we can also prove that the KerberizedRestTemplate is important by hitting the service without it:

@Test
public void givenRestTemplate_whenServiceCall_thenFail() {
    sampleClient.setRestTemplate(new RestTemplate());
    assertThrows(RestClientException.class, sampleClient::getData);
}

As a side note, there's a chance our second test could re-use the ticket already stored in the credential cache. This would happen due to the automatic SPNEGO negotiation used in HttpUrlConnection.

As a result, the data might actually return, invalidating our test. Depending on our needs, then, we can disable ticket cache usage through the system property http.use.global.creds=false.

5. Conclusion

In this tutorial, we explored Kerberos for centralized user management and how Spring Security supports the Kerberos protocol and SPNEGO authentication mechanism.

We used MiniKdc to stand up an embedded KDC and also created a very simple Kerberized client and server. This setup was handy for exploration and especially handy when we created an integration test to test things out.

Now, we've just scratched the surface. To dive deeper, check out the Kerberos wiki page or its RFC. Also, the official documentation page will be useful. Other than that,  to see how the things could be done in core java, the following Oracle's tutorial shows it in details.

As usual, the code can be found on our GitHub page.

Spring bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE
Security bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE
Comments are closed on this article!