{{announcement.body}}
{{announcement.title}}

Tutorial: Secure Your Java App in 5 Minutes With OAuth 2.0

DZone 's Guide to

Tutorial: Secure Your Java App in 5 Minutes With OAuth 2.0

In this article, we discuss how to secure a Java application in five minutes with OAuth 2.0 and Maven.

· Security Zone ·
Free Resource


Present-day apps depend on user authentication, which can be challenging for Java developers. Many developers build their own authentication service as a placeholder for a more powerful option only for that homegrown service to become a permanent solution. Through this post, I will show you how to integrate an enterprise auth service to a simple app as a solution to ending this heartbreak of a cycle. 

We’ll create an app that showcases user information. We’ll manually compose the authentication in the app to see the downsides. We’ll then move to the enterprise-auth solution. By the end of this post, you’ll learn how to secure a working Spring app using OAuth 2.0 for authentication in just 5 minutes.

Create Your Java Application with Spring

Let’s start by creating the project structure. You’ll use Spring Initializer to create the application. Go to start.spring.io and fill in the following information:


  • Project: Maven Project.
  • Language: Java.
  • Group: com.okta.authorizationapp.
  • Artifact: OAuth.
  • Dependencies:
    • Spring Web.
    • Spring Security.
    • Thymeleaf.
You may also like: Secure Spring REST With Spring Security and OAuth2.

You can also generate the project from the command line. Paste the following command in your terminal to download the project with the same configuration as above:

Shell




x


 
1
curl https://start.spring.io/starter.zip \
2
        -d dependencies=web,thymeleaf,security \
3
        -d packageName=com.okta.authorizationapp \
4
        -d name=authorization-app \
5
        -d type=maven-project \
6
        -o java-authorization-app.zip



That’s it! Now your Java project structure is created, and you can start developing your app.

Build User Security on Your Own

This tutorial will use Maven, but you can easily do it using Gradle if you prefer.

First, import the project in your favorite IDE/editor. Right now, your project has only one class, AuthorizationAppApplication that bootstraps the application. When you run this class, the server starts, and you can go to your browser to see the results.

However, you first need a page to access, so let’s create a home page.

Inside src/main/java/com/okta/authorizationapp/controller/, create the class, HomeController:

Java




xxxxxxxxxx
1
18


 
1
@Controller
2
public class HomeController {
3
 
          
4
    private Map<String, LocalDateTime> usersLastAccess = new HashMap<>();
5
 
          
6
    @GetMapping("/")
7
    public String getCurrentUser(@AuthenticationPrincipal User user, Model model) {
8
        String username = user.getUsername();
9
 
          
10
        model.addAttribute("username", username);
11
        model.addAttribute("lastAccess", usersLastAccess.get(username));
12
 
          
13
        usersLastAccess.put(username, LocalDateTime.now());
14
 
          
15
        return "home";
16
    }
17
}



This class defines a controller for the / path. When you access your app without defining any other path, this code will execute.

The controller’s first important action retrieves the current user’s information. Since you annotated your user attribute with AuthenticationPrincipal,Spring Security will automatically retrieve this information.

The controller also receives a model parameter that stores the data used to render the page. Right now, this data is the username and the last time the user accessed your application.

Create Dynamic Messages on User Login

The final step is to update the user’s last access date and define which HTML template should render the request. In your case, the endpoint is called, home. Spring will search for a home.html file inside the src/main/resources/templates folder.

You don’t have this file yet, so let’s go there and create it:

HTML




xxxxxxxxxx
1
11


 
1
<html>
2
  <head>
3
    <title>Java OAuth 2.0 Tutorial - Homepage</title>
4
  </head>
5
  <body>
6
    <h1 th:text="'Welcome, ' + ${username} + '!'"></h1>
7
    <ul>
8
      <li th:if="${lastAccess}" th:text="'Last access: ' + ${lastAccess}"></li>
9
    </ul>
10
  </body>
11
</html>



This is an HTML file altered slightly by Thymeleaf, one of the libraries you imported when you created the project. Thymeleaf receives the model object from the server and renders the values from it in HTML. Just type ${variable} to refer to a variable in the model object.

The th:text attribute will let you define a dynamic text in the HTML element. Here, we use it to display a dynamic greeting, and the last time the user accessed the application.

The first time a user accesses your app, there is no prior access recorded. To make sure you’re not presenting a meaningless field, use th:if. If the field is null, the li tag is not rendered, and the user won’t see it.

Add Basic Login to Your Java Spring App

Now, you have the endpoint, you just need to add security to your app.

Inside src/main/javacom/okta/authorizationapp/configuration/, create the class, SecurityConfiguration:

Java




xxxxxxxxxx
1
19


 
1
@EnableWebSecurity
2
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
3
 
          
4
    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
5
 
          
6
    @Override
7
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
8
        auth.inMemoryAuthentication()
9
                .passwordEncoder(passwordEncoder())
10
                .withUser("john.doe")
11
                .password(passwordEncoder().encode("secret"))
12
                .roles("USER");
13
    }
14
 
          
15
    @Bean
16
    public PasswordEncoder passwordEncoder() {
17
        return passwordEncoder;
18
    }
19
}



This class will ensure that users must log in to access your application. Right now there is only one user named john.doe who can log into the app.

Run the application by calling the main method inside AuthorizationAppApplication. You can also run it from the command line. Inside the project folder, run the following command:

Shell




xxxxxxxxxx
1


1
mvn spring-boot:run



When you go to http://localhost:8080 you should see the following login page:

Java Login

Type john.doe and secret as username and password. You should be redirected to the home page. On the first visit, only Welcome, john.doe! will display. From the second visit, you should also see the last access:

Homepage

You now have an application that manages security. Good job!

There is a big problem, though… Right now, you can only login with one user. Even worse, the user information is hardcoded in your app. To simplify user access and security, you can use Okta to manage your authentication.

It will provide you a very simple way to integrate with OAuth 2.0, in less than 5 minutes. Let’s configure OAuth 2.0 in your sample app to see how easy it is. Let’s start by creating an Okta account.

Create an Okta Account

If you don’t have an Okta account, go ahead and create one. Once you have signed up, go through the following steps:

  • Login to your account.
  • Click on Applications > Add Application.

You will be redirected to the following page:

Okta application page

Landing page
  • Select Web and click Next.

Fill in the following options in the form:

  • Name: hello-world
  • Base URIs: http://localhost:8080
  • Login redirect URLs: http://localhost:8080/login/oauth2/code/okta
  • Grant Type allowed:
    • Client Credentials.
    • Authorization Code.
  • Click Done.

Now, you can use your Okta application to authenticate users to your app.

Use OAuth 2.0: A Fast, Professional Approach

Let’s start by adding Okta’s library to your project.

Go to the pom.xml and add Okta’s Spring Boot starter:

HTML




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>com.okta.spring</groupId>
3
    <artifactId>okta-spring-boot-starter</artifactId>
4
    <version>1.3.0</version>
5
</dependency>



Okta will manage your app authentication, so you can delete the SecurityConfiguration class.

Inside HomeController, make the following changes:

Java




xxxxxxxxxx
1
13


 
1
@GetMapping("/")
2
public String getCurrentUser(@AuthenticationPrincipal OidcUser user, Model model) {
3
    String email = user.getEmail();
4
 
          
5
    model.addAttribute("email", email);
6
    model.addAttribute("lastAccess", usersLastAccess.get(email));
7
    model.addAttribute("firstName", user.getGivenName());
8
    model.addAttribute("lastName", user.getFamilyName());
9
 
          
10
    usersLastAccess.put(email, LocalDateTime.now());
11
 
          
12
    return "home";
13
}



Your endpoint will now receive an OidcUser compatible with OAuth 2.0. This class provides much more user information than you had before, so you can modify your HTML to display it. Replace username with email, and add firstName, and lastName, which are fields you didn’t have before. To do this, go to the hello.html and make the following changes:

HTML




xxxxxxxxxx
1


 
1
<body>
2
  <h1 th:text="'Welcome, ' + ${email} + '!'"></h1>
3
  <ul>
4
    <li th:if="${lastAccess}" th:text="'Last access: ' + ${lastAccess}"></li>
5
    <li th:if="${firstName}" th:text="'First name: ' + ${firstName}"></li>
6
    <li th:if="${lastName}" th:text="'Last name: ' + ${lastName}"></li>
7
  </ul>
8
</body>



You are still greeting the user as before, but you’re also displaying the new information from the endpoint. You have made all the code changes and now just need to add some configurations. Create an okta.env file in the root directory of your app with the following environment variables.

Shell




xxxxxxxxxx
1


 
1
export OKTA_OAUTH2_ISSUER=https://{yourOktaDomain}/oauth2/default
2
export OKTA_OAUTH2_CLIENT_ID={CLIENT_ID}
3
export OKTA_OAUTH2_CLIENT_SECRET={CLIENT_SECRET}



You will find {CLIENT_ID} and {CLIENT_SECRET} in the application’s page from the Okta dashboard. To access it, follow the steps below:


  • In your Okta dashboard, go to Applications.
  • Select the hello-world application.
  • Click on the General tab.

You should see both values in the Client Credentials area. Your {yourOktaDomain} will be visible in your Okta dashboard, just click on Dashboard in the menu. You will see the Org URL in the right upper corner.

Once you’ve pasted these values into okta.env, run the following commands to start your app.

Shell




xxxxxxxxxx
1


 
1
source okta.env
2
mvn spring-boot:run



That’s it!

Log Into Your Spring App With OAuth 2.0 Enabled

Navigate to http://localhost:8080. Your app will redirect you to Okta’s login page:

Okta Login Page

After logging in, you’ll be redirected to your application and see a message like this:

Java OAuth 2.0 User Info

Final Output


You’ve done it! In five minutes, you added OAuth 2.0 in your application with very little configuration along the way.

Learn More About Spring Security, Spring Boot and Java Authentication

If you want to take a look at the completed source code, you can access it on GitHub.

Do you want to read more about OAuth 2.0 and Java in general? You might be interested in the following articles:



Further Reading

Topics:
java ,oauth 2.0 ,security ,spring security ,spring boot ,tutorial ,authentication

Published at DZone with permission of Daniel Pereira . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}