How to authenticate users in a Java Spring Boot app
This guide provides detailed instructions on how to add user authentication via OneLogin to a Java Spring Boot application.
This application is based utilizes Spring Security’s OAuth2 Client to complete an OpenId Connect Authorization Code flow via OneLogin.
Follow the steps below to add user authentication.
- Configure OneLogin
- Configure the Java Spring Boot application to connect to OneLogin
- Start the application and login, logout.
View the sample code for this guide on Github
1. Configure OneLogin
Create a new OpenId Connect (OIDC) application from the OneLogin Administration panel.
Add a new App
Search for OIDC and select the OpenId Connect app
Create a display name for your app and Save.
Set a callback url. For this example, we will use http://localhost:8081/login to test.
On the SSO tab, note the Client ID and Client Secret. Then change the Token Endpoint Authentication Method to POST. Click Save.
Go to the Users section to locate your test user and assign the recently created application to that user.
2. Configure the application to connect to OneLogin
Get the sample app
Pull the source for the sample Spring Boot App from Github.
Setup environment variables
We will store our OIDC application credentials as environment variables.
/src/main/resources folder and update the
application.yml with your OneLogin account subdomain and your OIDC app client_id and client_secret.
security: oauth2: client: clientId: <your-onelogin-oidc-app-client-id> clientSecret: <}your-onelogin-oidc-app-client-secret> accessTokenUri: http://<subdomain>.onelogin.com/oidc/2/token userAuthorizationUri: http://<subdomain>.onelogin.com/oidc/2/auth tokenName: access_token authorizedGrantTypes: authorization_code scope: openid,profile,email resource: userInfoUri: http://<subdomain>.onelogin.com/oidc/2/me server: port : 8081
3. Start the application
It’s time to start the application and test our authentication flow.
This command makes the application available to test on http://localhost:8081/.
Click Login to start the authentication flow.
This triggers a GET request against the
/login route of your application and redirects you to secure login page hosted by OneLogin.
Enter username, password, and possibly MFA, depending on your security policy configuration in OneLogin.
Once authentication is complete, you’re redirected back to the
/login route of your local application and provided with an authorization code.
/login route passes the authorization code into OAuth2 client, which sends a POST request to OneLogin and exchanges the code for an Access Token.
The Access Token in turn is used to access resources by sending a request along with the token to the resource endpoint. In this case, we are retrieving information about the user by requesting data from the user info endpoint.
Clicking the logout button makes a request to the
/logout endpoint. The logout endpoint will terminate the users local session.