Implementing Single Sign-On (SSO) in Java Applications
Single Sign-On (SSO) is a session and user authentication process that allows a user to authenticate once and gain access to multiple applications or systems without having to log in repeatedly. In Java applications, SSO is typically implemented using industry standards like OAuth 2.0, OpenID Connect, SAML, and LDAP. SSO improves user experience and reduces the need for managing multiple credentials across systems.
Key Components of SSO
- Identity Provider (IdP):
- The IdP is responsible for authenticating the user and providing identity information. Examples of IdPs include Okta, Keycloak, Auth0, Google, and Microsoft Active Directory.
- Service Provider (SP):
- The SP is the application or service that relies on the IdP for authentication. After successful authentication with the IdP, the SP grants access to the user.
- Authentication Token:
- After successful authentication, the IdP issues an authentication token (e.g., JWT, SAML Assertion, or OAuth 2.0 Access Token). This token is used to authorize the user in subsequent applications.
- SSO Protocols:
- OAuth 2.0 and OpenID Connect are commonly used in modern web applications for SSO.
- SAML (Security Assertion Markup Language) is widely used in enterprise environments for SSO.
Benefits of SSO
- Improved User Experience: Users only need to authenticate once to access multiple services or applications.
- Centralized Authentication: User credentials are managed centrally, reducing the need for repeated logins and improving security.
- Reduced Password Fatigue: Users have fewer passwords to remember, which enhances usability.
- Security: By centralizing authentication, SSO can provide better security control over the login process and reduce the risk of password reuse.
Steps to Implement SSO in Java Applications
In this guide, we will focus on implementing SSO with OpenID Connect and OAuth 2.0 using Spring Boot for Java applications, leveraging Keycloak as the Identity Provider (IdP).
1. Set Up Keycloak as the Identity Provider (IdP)
- Install and Start Keycloak:
- Download and run the Keycloak server from Keycloak’s official website.
- Start Keycloak with the default port:
./bin/standalone.sh
- Create a Realm:
- Log into Keycloak’s admin console at
http://localhost:8080/auth/admin
. - Create a new realm (e.g.,
myrealm
).
- Log into Keycloak’s admin console at
- Create a Client:
- In the Keycloak Admin Console, navigate to the Clients section.
- Create a new client (e.g.,
myapp-client
), set the Client Protocol to OpenID Connect, and configure the Redirect URI to point to your Spring Boot application (e.g.,http://localhost:8081/*
).
- Set Up Roles and Users:
- Create roles (e.g.,
user
,admin
). - Add users with usernames and passwords to the Keycloak realm.
- Create roles (e.g.,
2. Configure Spring Boot for SSO
- Add Dependencies to
pom.xml
: Add the required dependencies for Spring Security and OAuth 2.0 Client:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
- Configure
application.yml
: Set the Keycloak as the authentication provider in yourapplication.yml
:spring: security: oauth2: client: registration: keycloak: client-id: myapp-client client-secret: YOUR_CLIENT_SECRET provider: keycloak authorization-grant-type: authorization_code scope: openid,profile,email redirect-uri: http://localhost:8081/login/oauth2/code/keycloak provider: keycloak: authorization-uri: http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/auth token-uri: http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token user-info-uri: http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/userinfo jwk-set-uri: http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/certs
ReplaceYOUR_CLIENT_SECRET
with the secret you generated when setting up the Keycloak client. - Configure Security Settings: Configure security settings to allow for login and secured endpoints using Keycloak’s OpenID Connect flow.
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .oauth2Login() .and() .logout() .logoutSuccessUrl("/home") .permitAll(); } }
- Create a Controller to Handle Login: You can create a simple controller to handle the home page and display user details after login:
@Controller public class HomeController { @GetMapping("/home") public String home(Model model, OAuth2AuthenticationToken authentication) { model.addAttribute("name", authentication.getPrincipal().getAttribute("name")); return "home"; } }
- Create a Simple Home View: Create a
home.html
view to display the authenticated user’s name:<html> <body> <h1>Welcome, ${name}!</h1> <a href="/logout">Logout</a> </body> </html>
3. Run the Application
- Start your Spring Boot application on port
8081
by running:mvn spring-boot:run
- When you access
http://localhost:8081/home
, you will be redirected to Keycloak for authentication. After successful authentication, you’ll be redirected back to the home page, showing the user’s name.
4. Testing the SSO Flow
- When you visit the protected
/home
page, the application will redirect to Keycloak for authentication. - Upon successful login, Keycloak will return an authorization code to the Spring Boot application, which will exchange it for an access token and ID token.
- The application will then retrieve user information from Keycloak and display it on the home page.