Technology and Security

Tag: Spring Boot

Send email from Spring Boot using Microsoft 365

Send Email using Spring Boot

This article is documents how to send email using Spring Boot over Microsoft 365 (formerly Office 365). Spring provides an easy to use interface called JavaMailSender that wraps the native JavaMail API. This example demonstrates sending both plain and HTML messages, as well as adding attachments.

Microsoft 365

Microsoft 365 subscriptions come with Outlook email access via browser or by native Office client applications. The Microsoft email solution (Outlook and Exchange) is ubiquitous for business users; It also offers the ability to connect from external clients for both sending and receiving messages. We will leverage this capability to send messages from a custom Java application.

JavaMailSender

Spring Boot provides this extended interface for JavaMail that supports MIME messages and completely handles session management. Messages containing attachments typically use this interface in conjunction with the MimeMessageHelper class.

Spring Boot Properties

Spring Boot pulls the mail settings from your default application.properties file (or YAML depending on your local setup). First set the properties to reference a Microsoft 365 (formerly Office 365) SMTP email host and enable security. Our GitHub repository should not contain sensitive property values, so externalize those variables.

// application.properties

spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.properties.mail.smtp.timeout=15000
spring.mail.properties.mail.smtp.connectiontimeout=15000
spring.mail.properties.mail.smtp.socketFactory.fallback=true
spring.mail.properties.mail.mail.debug=true

spring.config.import=sensitive.properties

Next add a spring.config.import statement to import sensitive.properties file, then provide the alternate file.

// sensitive.properties

spring.mail.username=my-user@mydomain.com
spring.mail.password=my-secure-password
prototype.o365.email.from=webmaster@mydomain.com
prototype.o365.email.to=destination-user@your-domain.com

Finally, to prevent sensitive.properties from finding its way to GitHub, be sure to update the .gitignore file to exclude it.

# .gitignore

### SENSITIVE PROPERTIES ###
sensitive*.properties

Send Email using Spring Boot

The final step is to craft and send your email. Use a SimpleMailMessage to send a plaintext email:

SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(emailTo);
msg.setFrom(emailFrom);
msg.setSubject("plain email at " + new Date().toString());
msg.setText("Hello World\n" + new Date().toString());

try
{
    javaMailSender.send(msg);
}
catch(MailException e)
{
    log.error("error sending plaintext email", e);
}

Use a MIME message to send HTML email content or include attachments:

MimeMessage msg = javaMailSender.createMimeMessage();
try
{
    MimeMessageHelper helper = 
        new MimeMessageHelper(msg, true);

    helper.setTo(emailTo);
    helper.setFrom(emailFrom);
    helper.setSubject("html email at " + new Date().toString());
    helper.setText("<h1>check attachment for the logo</h1>", true);

    helper.addAttachment("logo.png", 
        new ClassPathResource("logo.png"));
}
catch(MessagingException e)
{
    log.error("error preparing email", e);
}

try
{
    javaMailSender.send(msg);
}
catch(MailException e)
{
    log.error("error sending mime email", e);
}

Source Code

This article’s full source code is available on GitHub.

Sprint Boot Authentication with AzureAD Part 2

Spring Boot Authentication with Microsoft 365

In this second article of our series, we will start building a prototype that uses Spring Boot authentication to connect with Microsoft 365 Azure Active Directory (Azure AD). If you haven’t already completed part one of this series, please review that article now and create your Azure AD configuration.

Getting Started with Spring Initializr

In order to get the spring boot authentication prototype assembled quickly, first create an initial project structure using the Spring Initializr utility.

Spring Initializr, provided by the Pivotal, is a web application that will generate a Spring Boot project structure for you. Along with the structure, it provides a basic application class as well as either a Maven or a Gradle build script (we will use Gradle). The four primary Spring dependencies to import for our project include:

  • Azure Active Directory
  • OAUTH2 Client
  • Spring Web
  • Thymeleaf
Spring Initializr Settings
Spring Initializr Settings

Thymeleaf is a server-side Java templating engine for web applications. It has been around the block a few times, and does not have as much overhead as Angular so will keep our prototype example focused on authentication and easier to read.

Spring Initializr Project Structure

After making the dependency selections, click the “GENERATE” button to download the project file. As you can see from the snapshot below, Initializr has completed a fair amount of grunt work for our prototype.

Spring Boot Prototype Project Structure
Spring Boot Prototype Project Structure

Upgrading Versions in the Build Script

Spring Initializr choices can be a bit restrictive. At the time of this writing, the website only supports using version 2.5.8 while importing the Azure AD dependency. Selecting another version will give you the following error:

Spring Initializr Version Error for Azure AD
Spring Initializr Version Error for Azure AD

However, this is easily remedied by upgrading the versions in your build script after generating and downloading the project files.

Upgrade Spring Boot and Azure AD Versions
Upgrade Spring Boot and Azure AD Versions

We have upgraded both Spring Boot and Azure AD versions in the build.gradle script. Note that we have also upgraded the version of log4j to compensate for recent high profile vulnerabilities. Once Pivotal has upgraded the default log4j versions in Spring Boot, this log4j upgrade should no longer be necessary.

Sensitive Property Values

In part one of this series, we configured an Azure AD profile. During this step we created three values required for our prototype. These values should be treated as passwords. They should not be shared nor published to GitHub. Create the following file src/main/resources/sensitive.properties:

azure.activedirectory.tenant-id=your-azure-ad-tenant-id
azure.activedirectory.client-id=your-azure-ad--application-id
azure.activedirectory.client-secret=your-azure-ad-client-secret

Spring Boot Authentication Prototype

Our prototype is now stubbed out and ready for implementation. Part 3 of this series will focus on the code changes necessary to authenticate with Microsoft 365.

Spring Boot Authenticate With AzureAD

Spring Boot Authentication with Microsoft 365

In this first article of a multipart series, we will configure Microsoft 365 Azure Active Directory (Azure AD) to support building a web application that uses Spring Boot authentication. The official Microsoft documentation highlights key concepts for this process but rushes through several steps. In later articles we will build an example oauth2 authenticated application which uses this Azure AD configuration.

Spring Boot Authentication Overview

A number of steps are needed to build an oauth2 Spring Boot user authentication example using Azure AD. However, before we can begin coding we need an active Microsoft 365 Business subscription which is configured to support our web application. Once Microsoft 365 is configured, we can use properties obtained from the portal to bootstrap our Spring Boot starters for oauth2 and Azure AD.

What is Microsoft 365

Formerly known as Office 365, this monthly subscription from Microsoft is ubiquitous in the business world. Most customers purchase it for the core office applications and email, but it also includes an often overlooked feature. Most business subscription plans also include a license for a basic version of Azure AD, Microsoft’s LDAP Directory solution.

Prerequisites

For the purposes of this article, we’ll assume you have a typical small business setup. That means you already have a Microsoft 365 subscription, several user accounts, and have administrator access to the Microsoft portal.

Manage Azure AD

There are two primary ways to get to Azure AD via a web browser. You can either start at the top of the Microsoft portal and navigate your way through the maze, or just go directly to https://portal.azure.com. Once there, click on the button to view “Manage Azure Active Directory”

Manage Azure Active Directory
Manage Azure Active Directory

Register an Application in Azure AD

The first step in this configuration is to create a new application profile. Select “App Registrations” from the main menu in Azure AD and complete the form by adding a name, keeping the default options, and clicking the “Register” button.

Azure AD Register App
Azure AD Register App

The new application will be displayed with a number of system generated identifiers, as seen below.

Azure AD Application
Azure AD Application

These identifiers are sensitive, so treat them like passwords and keep them private. Two of these parameters will be needed for the Spring Boot authentication example application. Use the clipboard tooltip icon and make copies of the “Application (client) ID” and “Directory (tenant) ID” values and store them in a safe location for later.

Adding a Client Secret

Click the “New Client Secret” option from the “Certificates & Secrets” menu of your registered application.

Azure AD Add Client Secrets
Add Client Secrets

Add a “description” and select an “Expires” option from the form. Set the expiration length based on your company’s security policies and posture. Generally the shorter the expiry the better. But note that this value also greatly depends on your level of IT support staffing to determine how frequently the secret can be rotated and downstream applications updated.

Azure AD Client Secret Form
Add Client Secret Form

The generated client secret will contain several sensitive values that should be treated like passwords.

Azure AD Client Secret
Client Secret

Make a copy of the “Value” and store it in a safe location for later. You may also want to add the expiry date to an ops calendar so the rotation is not overlooked in the future.

Configure Platform Authentication

From the app registration, select the “Authentication” menu and then click “Add a platform“.

Azure AD Add Authentication Platform
Add Authentication Platform

Choose the “Web” option from the resulting “Configure platforms” form. Note that depending on your Microsoft 365 subscription level, you may see more platform options.

Azure AD Select Authentication Platform
Select Authentication Platform

Add a redirect URI to support local workstation development. You will need to choose a value that will not collide with any other routing within your system; The recommended default is seen below.

Azure AD Configure Authentication Platform
Configure Authentication Platform

The default “Redirect URI” can be copied below, and leave all other default values in place before clicking the “Configure” button.

http://localhost:8080/login/oauth2/code/

Create Application Roles

Now that we have the oauth2 routing configured for the application, we need to create application roles. An application’s roles will vary greatly depending on its purpose. For our example, we will only create an administrator (super user) role. In a real application, you most likely will have several roles supporting various types of functionality.

Select the “App roles” menu from the app registration, then click “Create app role“.

Azure AD Add Application Role
Add Application Role

Provide the form values then click “Apply“.

Azure AD Add Administrator Role
Add Administrator Role

There is some discretion on how you name the roles. For this example, set the value (used in the code) in all caps and the other values in proper case.

Assign Users and Groups

Select “Enterprise applications” from the Azure AD portal menu. Next select your application from the list of “All applications“. Finally, select “Users and groups” and click “Add user/group“.

Azure AD Assign Users
Assign Users

Select a user in your organization, then add a role and click “Assign“. If you created several roles earlier, lather rinse repeat on this process.

Azure AD Add Assignment
Add Assignment

Note that your Microsoft 365 subscription level will determine what assignments you can make; Basic subscriptions will only allow you to assign users directly (no group assignments).

Spring Boot User Authentication Example

This completes the basic setup for Azure AD. In the next article, we will use the Spring Boot Initialzr to start a new Java project using Gradle.

log4j vulnerabilities in spring boot

Spring Boot Updates for Log4J Vulnerabilities

Hackers continue to scan and exploit systems containing Log4J vulnerabilities at an unprecedented rate. On 10 December, the Spring Blog published detailed instructions for remediating Spring Boot applications using Maven or Gradle build scripts; Where this solution pattern is still accurate, the documented version is now out-of-date. Remember that even though the library may not be explicitly imported, it still might be present as a transitive dependency.

Latest Release for Log4J Vulnerabilities

The most secure version of Log4J is now version 2.17.1 (documented in our previous article). To force Spring Boot to import the most recent release of Log4J, include the following in your build scripts:

Maven

<properties>
    <log4j2.version>2.17.1</log4j2.version>
</properties>

Gradle

ext['log4j2.version'] = '2.17.1'

Powered by WordPress & Theme by Anders Norén