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
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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

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 With LDAP Authentication

Trending

  • Exploring Reactive and Proactive Observability in the Modern Monitoring Landscape
  • Understanding the Mandelbrot Set: A Beautiful Benchmark for Computing Power
  • How I Built an AI Portal for Document Q and A, Summarization, Transcription, Translation, and Extraction
  • Operationalizing Data Quality in Cloud ETL Workflows: Automated Validation and Anomaly Detection
  1. DZone
  2. Coding
  3. Frameworks
  4. Build Authentication the Easy Way with Spring Security 5.0 and OIDC

Build Authentication the Easy Way with Spring Security 5.0 and OIDC

Spring Security 5.0 offers a host of new tools for your authentication needs. Let's see how to use it and OIDC together to secure your Spring-based apps.

By 
Matt Raible user avatar
Matt Raible
·
Feb. 02, 18 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
45.6K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Security is not just a powerful and highly customizable authentication and access-control framework, it is also the de-facto standard for securing Spring-based applications. Once upon a time Spring Security required reams of XML to configure everything, but those days are long past. These days, Spring Security offers much simpler configuration via Spring’s JavaConfig. If you look at the SecurityConfiguration.java class from the JHipster OIDC example I wrote about recently, you’ll see it’s less than 100 lines of code!

Spring Security 5.0 resolves 400+ tickets, and has a plethora of new features:

  • OAuth 2.0 Login
  • Reactive Support: @EnableWebFluxSecurity, @EnableReactiveMethodSecurity, and WebFlux Testing Support
  • Modernized Password Encoding

Today, I’ll be showing you how to utilize the OAuth 2.0 Login support with Okta. I’ll also show you to retrieve a user’s information via OpenID Connect (OIDC).

You know that Okta offers free developer accounts with up to 7,000 active monthly users, right? That should be enough to get your killer app off the ground.

Spring Security makes authentication with OAuth 2.0 pretty darn easy. It also provides the ability to fetch a user’s information via OIDC. Follow the steps below to learn more!

What is OIDC? If you’re not familiar with OAuth or OIDC, I recommend you read What the Heck is OAuth. An Open ID Connect flow involves the following steps:

  1. Discover OIDC metadata
  2. Perform OAuth flow to obtain ID token and access tokens
  3. Get JWT signature keys and optionally dynamically register the Client application
  4. Validate JWT ID token locally based on built-in dates and signature
  5. Get additional user attributes as needed with access token

OIDC Flow

Create a Spring Boot App

Open start.spring.io in your browser. Spring Initialzr is a site that allows you to create new Spring Boot applications quickly and easily. Set the Spring Boot version (in the top right corner) to 2.0.0.M7. Type in a group and artifact name. As you can see from the screenshot below, I chose com.okta.developer and oidc. For dependencies, select Web, Reactive Web, Security, and Thymeleaf.

start.spring.io

Click Generate Project, download the zip, expand it on your hard drive, and open the project in your favorite IDE. Run the app with ./mvnw spring-boot:run, and you’ll be prompted to log in.

Default Login

Spring Security 4.x prompts you with basic authentication rather than with a login form, so this is one thing that’s different with Spring Security 5.

The Spring Security starter creates a default user with username “user” and a password that changes every time you start the application. You can find this password in your terminal, similar to the one below.

Using default security password: 103c55b4-2760-4830-9bca-a06a87d384f9


In the form, enter “user” for the User and the generated password for Password. The next screen will be a 404 since your app doesn’t have a default route configured for the / path.

Post Login

In Spring Boot 1.x, you could change the user’s password, so it’s the same every time by adding the following to src/main/resources/application.properties.

security.user.password=spring security is ph@!


However, this is a deprecated feature in Spring Boot 2.0. The good news is this change will likely be reverted before a GA release.

In the meantime, you can copy the password that’s printed to your console and use it with HTTPie.

$ http --auth user:'bf91316f-f894-453a-9268-4826cdd7e151' localhost:8080
HTTP/1.1 404
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json;charset=UTF-8
Date: Sun, 03 Dec 2017 19:11:50 GMT
Expires: 0
Pragma: no-cache
Set-Cookie: JSESSIONID=65283FCBDB9E6EF1C0679290AA994B0D; Path=/; HttpOnly
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block


The response will be a 404 as well.

{
   "error": "Not Found",
   "message": "No message available",
   "path": "/",
   "status": 404,
   "timestamp": "2017-12-03T19:11:50.846+0000"
}


You can get rid of the 404 by creating a MainController.java in the same directory as OidcApplication.java (src/main/java/com/okta/developer/oidc). Create a home() method that maps to / and returns the user’s name.

package com.okta.developer.oidc;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
public class MainController {

   @GetMapping("/")
   String home(Principal user) {
       return "Hello " + user.getName();
   }
}


Restart your server, log in with user and the generated password and you should see Hello user.

$ http --auth user:'d7c4138d-a1cc-4cc9-8975-97f37567594a' localhost:8080
HTTP/1.1 200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 10
Content-Type: text/plain;charset=UTF-8
Date: Sun, 03 Dec 2017 19:26:54 GMT
Expires: 0
Pragma: no-cache
Set-Cookie: JSESSIONID=22A5A91051B7AFBA1DC8BD30C0B53365; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Hello user


Add Authentication With Okta

In a previous tutorial, I showed you how to use Spring Security OAuth to provide SSO to your apps. You can do the same thing in Spring Security 5, but you can also specify multiple providers now, which you couldn’t do previously. Spring Security 5 has a OAuth 2.0 Login sample, and documentation on how everything works.

Create an OpenID Connect App

To integrate with Okta, you’ll need to sign up for an account on developer.okta.com. After confirming your email and logging in, navigate to Applications > Add Application. Click Web and then click Next. Give the app a name you’ll remember, specify http://localhost:8080 as a Base URI, as well as http://localhost:8080/login/oauth2/code/okta for a Login redirect URI.

Rename src/main/resources/application.properties to src/main/resources/application.yml and populate it with the following.

spring:
 thymeleaf:
   cache: false
 security:
   oauth2:
     client:
       registration:
         okta:
           client-id: {clientId}
           client-secret: {clientSecret}
       provider:
         okta:
           authorization-uri: https://{yourOktaDomain}.com/oauth2/default/v1/authorize
           token-uri: https://{yourOktaDomain}.com/oauth2/default/v1/token
           user-info-uri: https://{yourOktaDomain}.com/oauth2/default/v1/userinfo
           jwk-set-uri: https://{yourOktaDomain}.com/oauth2/default/v1/keys


Copy the client ID and secret from your OIDC app into your application.yml file. For {yourOktaDomain}, use the value of your domain (e.g. dev-158606.oktapreview.com). Make sure it does not include -admin in it.

You’ll need to add some dependencies to your pom.xml for Spring Security 5’s OAuth configuration to initialize correctly.

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>


Restart your app and navigate to http://localhost:8080 again. You’ll see a link to click on to log in with Okta.

Login with OAuth 2.0

NOTE: If you’d like to learn how to customize the login screen that Spring Security displays, see its OAuth 2.0 Login Page documentation.

After clicking on the link, you should see a login screen.

Okta Login

Enter the credentials you used to create your account, and you should see a screen like the following after logging in.

Okta Login

NOTE: It’s possible to change things so Principal#getName() returns a different value. However, there is a bug in Spring Boot 2.0.0.M7 that prevents the configuration property from working.

Get User Information With OIDC

Change your MainController.java to have the code below. This code adds a /userinfo mapping that uses Spring WebFlux’s WebClient to get the user’s information from the user info endpoint. I copied the code below from Spring Security 5’s OAuth 2.0 Login sample.

/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.okta.developer.oidc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.Map;

/**
* @author Joe Grandja
*/
@Controller
public class MainController {

   private final OAuth2AuthorizedClientService authorizedClientService;

   public MainController(OAuth2AuthorizedClientService authorizedClientService) {
       this.authorizedClientService = authorizedClientService;
   }

   @RequestMapping("/")
   public String index(Model model, OAuth2AuthenticationToken authentication) {
       OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
       model.addAttribute("userName", authentication.getName());
       model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
       return "index";
   }

   @RequestMapping("/userinfo")
   public String userinfo(Model model, OAuth2AuthenticationToken authentication) {
       OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
       Map userAttributes = Collections.emptyMap();
       String userInfoEndpointUri = authorizedClient.getClientRegistration()
               .getProviderDetails().getUserInfoEndpoint().getUri();
       if (!StringUtils.isEmpty(userInfoEndpointUri)) {    // userInfoEndpointUri is optional for OIDC Clients
           userAttributes = WebClient.builder()
                   .filter(oauth2Credentials(authorizedClient)).build()
                   .get().uri(userInfoEndpointUri)
                   .retrieve()
                   .bodyToMono(Map.class).block();
       }
       model.addAttribute("userAttributes", userAttributes);
       return "userinfo";
   }

   private OAuth2AuthorizedClient getAuthorizedClient(OAuth2AuthenticationToken authentication) {
       return this.authorizedClientService.loadAuthorizedClient(
               authentication.getAuthorizedClientRegistrationId(), authentication.getName());
   }

   private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
       return ExchangeFilterFunction.ofRequestProcessor(
               clientRequest -> {
                   ClientRequest authorizedRequest = ClientRequest.from(clientRequest)
                           .header(HttpHeaders.AUTHORIZATION,
                                   "Bearer " + authorizedClient.getAccessToken().getTokenValue())
                           .build();
                   return Mono.just(authorizedRequest);
               });
   }
}


Create a Thymeleaf index page at src/main/resources/templates/index.html. You can use Thymeleaf’s support for Spring Security to show/hide different parts of the page based on the user’s authenticated status.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
     xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
   <title>Spring Security - OAuth 2.0 Login</title>
   <meta charset="utf-8" />
</head>
<body>
<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()">
   <div style="float:left">
       <span style="font-weight:bold">User: </span><span sec:authentication="name"></span>
   </div>
   <div style="float:none">&nbsp;</div>
   <div style="float:right">
       <form action="#" th:action="@{/logout}" method="post">
           <input type="submit" value="Logout" />
       </form>
   </div>
</div>
<h1>OAuth 2.0 Login with Spring Security</h1>
<div>
   You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>
   via the OAuth 2.0 Client <span style="font-weight:bold" th:text="${clientName}"></span>
</div>
<div>&nbsp;</div>
<div>
   <a href="/userinfo" th:href="@{/userinfo}">Display User Info</a>
</div>
</body>
</html>


Create another template at src/main/resources/userinfo.html to display the user’s attributes.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
   <title>Spring Security - OAuth 2.0 User Info</title>
   <meta charset="utf-8" />
</head>
<body>
<div th:replace="index::logout"></div>
<h1>OAuth 2.0 User Info</h1>
<div>
   <span style="font-weight:bold">User Attributes:</span>
   <ul>
       <li th:each="userAttribute : ${userAttributes}">
           <span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span>
       </li>
   </ul>
</div>
</body>
</html>


Now, when you’re logged in, you’ll see a link to display user info.

Index Page

Click on the link, and you’ll see the contents of the ID Token that’s retrieved from the user info endpoint.

UserInfo Page

Learn More About Spring Security and OIDC

This article showed you how to implement login with OAuth 2.0 and Spring Security 5. I also showed you how to use OIDC to retrieve a user’s information. The source code for the application developed in this article can be found on GitHub.

These resources provide additional information about Okta and OIDC:

  • Okta Developer Documentation and its OpenID Connect API
  • Identity, Claims, & Tokens – An OpenID Connect Primer, Part 1 of 3
  • OIDC in Action – An OpenID Connect Primer, Part 2 of 3
  • What’s in a Token? – An OpenID Connect Primer, Part 3 of 3
  • Add Role-Based Access Control to Your App with Spring Security and Thymeleaf

If you have any questions about this post, please leave a comment below. You can also post to Stack Overflow with the okta tag or use our developer forums.

Get Started with Spring Security 5.0 and OIDC was originally published on the Okta developer blog on December 18, 2017.

Spring Security Spring Framework authentication

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 With LDAP Authentication

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: