DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC
  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood
  • Spring Security Oauth2: Google Login

Trending

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • The Evolution of Scalable and Resilient Container Infrastructure
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  1. DZone
  2. Coding
  3. Frameworks
  4. Get Started With Spring Boot, SAML, and Okta

Get Started With Spring Boot, SAML, and Okta

Here we dive into security, covering how to use Okta and SAML for the authentication and authorization of your Spring Boot apps.

By 
Matt Raible user avatar
Matt Raible
·
Jul. 17, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
44.1K Views

Join the DZone community and get the full member experience.

Join For Free

Today I’d like to show you how to build a Spring Boot application that leverages Okta’s Platform API for authentication via SAML. SAML (Security Assertion Markup Language) is an XML-based standard for securely exchanging authentication and authorization information between entities — specifically between identity providers, service providers, and users. Well-known IdPs include Salesforce, Okta, OneLogin, and Shibboleth.

My Okta developer experience began a couple years ago (in December 2014) when I worked for a client that was adopting it. I was tasked with helping them decide on a web framework to use, so I built prototypes with Node, Ruby, and Spring. I documented my findings in a blog post. Along the way, I tweeted my issues with Spring Boot, and asked how to fix it on Stack Overflow. I ended up figuring out the solution through trial-and-error and my findings made it into the official Spring documentation. Things have changed a lot since then and now Spring Security 4.2 has support for auto-loading custom DSLs. And guess what, there’s even a DSL for SAML configuration!

Ready to get started? You can follow along in with the written tutorial below, check out the code on GitHub, or watch the screencast I made to walk you through the same process.


Sign Up for an Okta Developer Account

Fast forward two years, and I find myself as an Okta employee. To start developing with Okta, I created a new developer account at https://developer.okta.com. Make sure you take a screenshot or write down your Okta URL after you’ve signed up. You’ll need this URL to get back to the admin console.

You’ll receive an email to activate your account and change your temporary password. After completing these steps, you’ll land on your dashboard with some annotations about “apps”.

Create a SAML Application on Okta

At the time of this writing, the easiest way to create a SAML-aware Spring Boot application is to use Spring Security’s SAML DSL project. It contains a sample project that provides instructions for configuring Okta as a SAML provider. These instructions will likely work for you if you’re experienced Spring Boot and Okta developer. If you’re new to both, this “start from scratch” tutorial might work better for you.

Just like I did, the first thing you’ll need to do is create a developer account at https://developer.okta.com. After activating your account, login to it and click on the “Admin” button in the top right.

Okta UserHome

On the next screen, click “Add Applications” in the top right.

Okta Dashboard

This will bring you to a screen with a “Create New App” green button on the left.

Create New App

Click the button and choose “Web” for the platform and “SAML 2.0” for the sign on method.

New App with SAML 2.0

Click the “Create” button. The next screen will prompt you for an application name. I used “Spring SAML”, but any name will work.

Enter App name

Click the “Next” button. This brings you to the second step, configuring SAML. Enter the following values:

  • Single sign on URL: https://localhost:8443/saml/SSO
  • Audience URI: https://localhost:8443/saml/metadata

SAML Integration

Scroll to the bottom of the form and click “Next”. This will bring you to the third step, feedback. Choose “I’m an Okta customer adding an internal app” and optionally select the App type.

Customer or Partner

Click the “Finish” button to continue. This will bring you to the application’s “Sign On” tab which has a section with a link to your application's metadata in a yellow box. Copy the Identity Provider metadata link as you’ll need it to configure your Spring Boot application.

SAML Metadata

The final setup step you’ll need is to assign people to the application. Click on the “People” tab and the “Assign to People” button. You’ll see a list of people with your account in it.

Assign People

Click the assign button, accept the default username (your email), and click the “Done” button.

Create a Spring Boot Application With SAML Support

Navigate to https://start.spring.io in your favorite browser and select Security, Web, Thymeleaf, and DevTools as dependencies.

start.spring.io

Click “Generate Project”, download the generated ZIP file and open it in your favorite editor. Add the spring-security-saml-dsl dependency to your pom.xml.

<dependency>
    <groupId>org.springframework.security.extensions</groupId>
    <artifactId>spring-security-saml-dsl</artifactId>
    <version>1.0.0.M3</version>
</dependency>


You’ll also need to add the Spring Milestone repository since a milestone release is all that’s available at the time of this writing.

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone</url>
    </repository>
</repositories>


If you’d like to see instructions for Gradle, please view the project’s README.md.

In src/main/resources/application.properties, add the following key/value pairs. Make sure to use the “Identity Provider metadata” value you copied earlier (hint: you can find it again under the “Sign On” tab in your Okta application).

server.port = 8443
server.ssl.enabled = true
server.ssl.key-alias = spring
server.ssl.key-store = src/main/resources/saml/keystore.jks
server.ssl.key-store-password = secret

security.saml2.metadata-url = <your metadata url>


From a terminal window, navigate to the src/main/resources directory of your app and create a saml directory. Navigate into the directory and run the following command. Use “secret” when prompted for a keystore password.

keytool -genkey -v -keystore keystore.jks -alias spring -keyalg RSA -keysize 2048 -validity 10000


The values for the rest of the questions don’t matter since you’re not generating a real certificate. However, you will need to answer “yes” to the following question.


Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
  [no]:


Create a SecurityConfiguration.java file in the com.example package.

package com.example;

import static org.springframework.security.extensions.saml2.config.SAMLConfigurer.saml;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Value("${security.saml2.metadata-url}")
    String metadataUrl;

    @Value("${server.ssl.key-alias}")
    String keyAlias;

    @Value("${server.ssl.key-store-password}")
    String password;

    @Value("${server.port}")
    String port;

    @Value("${server.ssl.key-store}")
    String keyStoreFilePath;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/saml*").permitAll()
                .anyRequest().authenticated()
                .and()
            .apply(saml())
                .serviceProvider()
                    .keyStore()
                        .storeFilePath("saml/keystore.jks")
                        .password(this.password)
                        .keyname(this.keyAlias)
                        .keyPassword(this.password)
                        .and()
                    .protocol("https")
                    .hostname(String.format("%s:%s", "localhost", this.port))
                    .basePath("/")
                    .and()
                .identityProvider()
                .metadataFilePath(this.metadataUrl);
    }
}


Create an IndexController.java file in the same directory and use it to set the default view to index.

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}


Since you chose Thymeleaf when creating your application, you can create a src/main/resources/templates/index.html and it will automatically be rendered after you sign-in. Create this file and populate it with the following HTML.

<!DOCTYPE html>
<html>
<head>
    <title>Spring Security SAML Example</title>
</head>
<body>
Hello SAML!
</body>
</html>


Run the App and Login With Okta

Start the app using your IDE or mvn spring-boot:run and navigate to https://localhost:8443. If you’re using Chrome, you’ll likely see a privacy error.

Connection Not Private

Click the “ADVANCED” link at the bottom. Then click the “proceed to localhost (unsafe)” link.

Proceed to localhost

Next, you’ll be redirected to Okta to sign in and redirected back to your app. If you’re already logged in, you won’t see anything from Okta. If you sign out from Okta, you’ll see a login screen such as the one below.

Okta Login

After you’ve logged in, you should see a screen like the one below.

Hello SAML

Spring Security authentication Spring Framework Spring Boot

Published at DZone with permission of Matt Raible, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC
  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood
  • Spring Security Oauth2: Google Login

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!