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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll understand the Generic Security Service API (GSS API) and how we can implement it in Java. We’ll see how we can secure network communication using the GSS API in Java.

In the process, we’ll create simple client and server components, securing them with GSS API.

2. What Is GSS API?

So, what really is the Generic Security Service API? GSS API provides a generic framework for applications to use different security mechanisms like Kerberos, NTLM, and SPNEGO in a pluggable manner. Consequently, it helps applications to decouple themselves from the security mechanisms directly.

To clarify, security here spans authentication, data integrity, and confidentiality.

2.1. Why Do We Need GSS API?

Security mechanisms like Kerberos, NTLM, and Digest-MD5 are quite different in their capabilities and implementations. Typically, an application supporting one of these mechanisms finds it quite daunting to switch to another.

This is where a generic framework like GSS API provides applications with an abstraction. Therefore applications using GSS API can negotiate a suitable security mechanism and use that for communication. All that without actually having to implement any mechanism-specific details.

2.2. How Does GSS API Work?

GSS API is a token-based mechanism. It works by the exchange of security tokens between peers. This exchange typically happens over a network but GSS API is agnostic to those details.

These tokens are generated and processed by the specific implementations of the GSS API. The syntax and semantics of these tokens are specific to the security mechanism negotiated between the peers:

Screenshot-2019-08-12-at-12.08.43

The central theme of GSS API revolves around a security context. We can establish this context between peers through the exchange of tokens. We may need multiple exchanges of tokens between peers to establish the context.

Once successfully established at both the ends, we can use the security context to exchange data securely. This may include data integrity checks and data encryption, depending upon the underlying security mechanism.

3. GSS API Support in Java

Java supports GSS API as part of the package “org.ietf.jgss”. The package name may seem peculiar. That’s because the Java bindings for GSS API are defined in an IETF specification. The specification itself is independent of the security mechanism.

One of the popular security mechanism for Java GSS is Kerberos v5.

3.1. Java GSS API

Let’s try to understand some of the core APIs that builds Java GSS:

  • GSSContext encapsulates the GSS API security context and provides services available under the context
  • GSSCredential encapsulates the GSS API credentials for an entity that is necessary to establish the security context
  • GSSName encapsulates the GSS API principal entity which provides an abstraction for different namespace used by underlying mechanisms

Apart from the above interfaces, there are few other important classes to note:

  • GSSManager serves as the factory class for other important GSS API classes like GSSName, GSSCredential, and GSSContext
  • Oid represents the Universal Object Identifiers (OIDs) which are hierarchical identifiers used within GSS API to identify mechanisms and name formats
  • MessageProp wraps properties to indicate GSSContext on things like Quality of Protection (QoP) and confidentiality for data exchange
  • ChannelBinding encapsulates the optional channel binding information used to strengthen the quality with which peer entity authentication is provided

3.2. Java GSS Security Provider

While the Java GSS defines the core framework for implementing the GSS API in Java, it does not provide an implementation. Java adopts Provider-based pluggable implementations for security services including Java GSS.

There can be one or more such security providers registered with the Java Cryptography Architecture (JCA). Each security provider may implement one or more security services, like Java GSSAPI and security mechanisms underneath.

There is a default GSS provider that ships with the JDK. However, there are other vendor-specific GSS providers with different security mechanisms which we can use. One such provider is IBM Java GSS. We have to register such a security provider with JCA to be able to use them.

Moreover, if required, we can implement our own security provider with possibly custom security mechanisms. However, this is hardly needed in practice.

4. GSS API Through an Example

Now, we’ll see Java GSS in action through an example. We’ll create a simple client and server application. The client is more commonly referred to as initiator and server as an acceptor in GSS. We’ll use Java GSS and Kerberos v5 underneath for authentication.

4.1. GSS Context for Client and Server

To begin with, we’ll have to establish a GSSContext, both at the server and client-side of the application.

Let’s first see how we can do this at the client-side:

GSSManager manager = GSSManager.getInstance();
String serverPrinciple = "HTTP/[email protected]";
GSSName serverName = manager.createName(serverPrinciple, null);
Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
GSSContext clientContext = manager.createContext(
  serverName, krb5Oid, (GSSCredential)null, GSSContext.DEFAULT_LIFETIME);
clientContext.requestMutualAuth(true);
clientContext.requestConf(true);
clientContext.requestInteg(true);

There is quite a lot of things happening here, let’s break them down:

  • We begin by creating an instance of the GSSManager
  • Then we use this instance to create GSSContext, passing along:
    • a GSSName representing the server principal, note the Kerberos specific principal name here
    • the Oid of mechanism to use, Kerberos v5 here
    • the initiator’s credentials, null here means that default credentials will be used
    • the lifetime for the established context
  • Finally, we prepare the context for mutual authentication, confidentiality, and data integrity

Similarly, we have to define the server-side context:

GSSManager manager = GSSManager.getInstance();
GSSContext serverContext = manager.createContext((GSSCredential) null);

As we can see, this is much simpler than the client-side context. The only difference here is that we need acceptor’s credentials which we have used as null. As before, null means that the default credentials will be used.

4.2. GSS API Authentication

Although we have created the server and client-side GSSContext, please note that they are unestablished at this stage.

To establish these contexts, we need to exchange tokens specific to the security mechanism specified, that is Kerberos v5:

// On the client-side
clientToken = clientContext.initSecContext(new byte[0], 0, 0);
sendToServer(clientToken); // This is supposed to be send over the network
		
// On the server-side
serverToken = serverContext.acceptSecContext(clientToken, 0, clientToken.length);
sendToClient(serverToken); // This is supposed to be send over the network
		
// Back on the client side
clientContext.initSecContext(serverToken, 0, serverToken.length);

This finally makes the context established at both the ends:

assertTrue(serverContext.isEstablished());
assertTrue(clientContext.isEstablished());

4.3. GSS API Secure Communication

Now, that we have context established at both the ends, we can start sending data with integrity and confidentiality:

// On the client-side
byte[] messageBytes = "Baeldung".getBytes();
MessageProp clientProp = new MessageProp(0, true);
byte[] clientToken = clientContext.wrap(messageBytes, 0, messageBytes.length, clientProp);
sendToClient(serverToken); // This is supposed to be send over the network
       
// On the server-side 
MessageProp serverProp = new MessageProp(0, false);
byte[] bytes = serverContext.unwrap(clientToken, 0, clientToken.length, serverProp);
String string = new String(bytes);
assertEquals("Baeldung", string);

There are a couple of things happening here, let’s analyze:

  • MessageProp is used by the client to set the wrap method and generate the token
  • The method wrap also adds cryptographic MIC of the data, the MIC is bundled as part of the token
  • That token is sent to the server (possibly over a network call)
  • The server leverages MessageProp again to set the unwrap method and get data back
  • Also, the method unwrap verifies the MIC for the received data, ensuring the data integrity

Hence, the client and server are able to exchange data with integrity and confidentiality.

4.4. Kerberos Set-up for the Example

Now, a GSS mechanism like Kerberos is typically expected to fetch credentials from an existing Subject. The class Subject here is a JAAS abstraction representing an entity like a person or a service. This is usually populated during a JAAS-based authentication.

However, for our example, we’ll not directly use a JAAS-based authentication. We’ll let Kerberos obtain credentials directly, in our case using a keytab file. There is a JVM system parameter to achieve that:

-Djavax.security.auth.useSubjectCredsOnly=false

However, the defaults Kerberos implementation provided by Sun Microsystem relies on JAAS to provide authentication.

This may sound contrary to what we just discussed. Please note that we can explicitly use JAAS in our application which will populate the Subject. Or leave it to the underlying mechanism to authenticate directly, where it anyways uses JAAS. Hence, we need to provide a JAAS configuration file to the underlying mechanism:

com.sun.security.jgss.initiate  {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  keyTab=example.keytab
  principal="client/localhost"
  storeKey=true;
};
com.sun.security.jgss.accept  {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  keyTab=example.keytab
  storeKey=true
  principal="HTTP/localhost";
};

This configuration is straight-forward, where we have defined Kerberos as the required login module for both initiator and acceptor. Additionally, we have configured to use the respective principals from a keytab file. We can pass this JAAS configuration to JVM as a system parameter:

-Djava.security.auth.login.config=login.conf

Here, the assumption is that we have access to a Kerberos KDC. In the KDC we have set up the required principals and obtained the keytab file to use, let’s say “example.keytab”.

Additionally, we need the Kerberos configuration file pointing to the right KDC:

[libdefaults]
default_realm = EXAMPLE.COM
udp_preference_limit = 1
[realms]
EXAMPLE.COM = {
    kdc = localhost:52135
}

This simple configuration defines a KDC running on port 52135 with a default realm as EXAMPLE.COM. We can pass this to JVM as a system parameter:

-Djava.security.krb5.conf=krb5.conf

4.5. Running the Example

To run the example, we have to make use of the Kerberos artifacts discussed in the last section.

Also, we need to pass the required JVM parameters:

java -Djava.security.krb5.conf=krb5.conf \
  -Djavax.security.auth.useSubjectCredsOnly=false \
  -Djava.security.auth.login.config=login.conf \
  com.baeldung.jgss.JgssUnitTest

This is sufficient for Kerberos to perform the authentication with credentials from keytab and GSS to establish the contexts.

5. GSS API in Real World

While GSS API promises to solve a host of security problems through pluggable mechanisms, there are few use cases which have been more widely adopted:

  • It’s widely used in SASL as a security mechanism, especially where Kerberos is the underlying mechanism of choice. Kerberos is a widely used authentication mechanism, especially within an enterprise network. It is really useful to leverage a Kerberised infrastructure to authenticate a new application. Hence, GSS API bridges that gap nicely.
  • It’s also used in conjugation with SPNEGO to negotiate a security mechanism when one is not known beforehand. In this regard, SPNEGO is a pseudo mechanism of GSS API in a sense. This is widely supported in all modern browsers making them capable of leveraging Kerberos-based authentication.

6. GSS API in Comparision

GSS API is quite effective in providing security services to applications in a pluggable manner. However, it’s not the only choice to achieve this in Java.

Let’s understand what else Java has to offer and how do they compare against GSS API:

  • Java Secure Socket Extension (JSSE): JSSE is a set of packages in Java that implements Secure Sockets Layer (SSL) for Java. It provides data encryption, client and server authentication, and message integrity. Unlike GSS API, JSSE relies on a Public Key Infrastructure (PKI) to work. Hence, the GSS API works out to be more flexible and lightweight than JSSE.
  • Java Simple Authentication and Security Layer (SASL): SASL is a framework for authentication and data security for internet protocols which decouples them from specific authentication mechanisms. This is similar in scope to GSS API. However, Java GSS has limited support for underlying security mechanisms through available security providers.

Overall, GSS API is pretty powerful in providing security services in mechanism agnostic manner. However, support for more security mechanisms in Java will take this further in adoption.

7. Conclusion

To sum up, in this tutorial, we understood the basics of GSS API as a security framework. We went through the Java API for GSS and understood how we can leverage them. In the process, we created simple client and server components that performed mutual authentication and exchanged data securely.

Further, we also saw what are the practical applications of GSS API and what are the alternatives available in Java.

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)