Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

NPI – Frontegg – Security – (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

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.

Introduction to SPNEGO/Kerberos Authentication in Spring provides an in-depth overview of the technology.

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 AbstractHttpConfigurer<WebSecurityConfig, HttpSecurity> {

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

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

    public static WebSecurityConfig securityConfig() {
        return new WebSecurityConfig();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        AuthenticationManager authenticationManager = 
        http.getSharedObject(AuthenticationManager.class);
        http.addFilterBefore(spnegoAuthenticationProcessingFilter(authenticationManager),
           BasicAuthenticationFilter.class);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.exceptionHandling()
            .authenticationEntryPoint(spnegoEntryPoint())
            .and()
            .authorizeRequests()
            .antMatchers("/", "/home")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and()
            .apply(securityConfig());
        return http.build();
    }

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
            .authenticationProvider(kerberosAuthenticationProvider())
            .authenticationProvider(kerberosServiceAuthenticationProvider())
            .build();
    }

    @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();
	<span class="hljs-comment">// validator configuration</span>
	return ticketValidator;
    }

}

The intro article contains all the implementation above, so we're omitting the full methods here for brevity.

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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

Security footer banner
Comments are closed on this article!