eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

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]

If we are working with JDK 9 or later, we need to enable the java.security.jgss module in our IDEs in order to start the MiniKdc successfully. We can do this through a command line parameter that we can set during the execution of the Main class:

--add-exports java.security.jgss/sun.security.krb5=ALL-UNNAMED

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();
	// validator configuration
	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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)