Secure Your Spring Boot Backend and Angular Frontend with Okta
Securing a Spring Boot backend and Angular frontend with Okta involves integrating authentication and authorization into both the backend and frontend using Okta's Identity Management platform. Here's a step-by-step guide:
Backend (Spring Boot with Okta OAuth2 Integration)
1. Set Up Okta Developer Account
- Go to Okta Developer and create an account.
- Once logged in, create a new OAuth 2.0 Application in the Okta dashboard:
- Choose Web as the platform.
- Set up the Redirect URI to
http://localhost:8080/login/oauth2/code/okta
for local development. - Set Grant Type to Authorization Code.
- After creating the app, note the Client ID, Client Secret, and Issuer URL (e.g.,
https://dev-XXXX.okta.com/oauth2/default
).
2. Add Dependencies to pom.xml
Add the required dependencies for Spring Security OAuth2 and Okta to your pom.xml
:
3. Configure application.yml
In src/main/resources/application.yml
, configure your Okta OAuth2 settings:
4. Configure Spring Security
Create a SecurityConfig
class to secure your application routes:
In this configuration:
/
,/login
, and/error
are publicly accessible.- All other routes require authentication via OAuth2 login.
5. Create a Controller
Create a simple controller to test the secured and public routes:
6. Run the Spring Boot Application
Start the Spring Boot application (mvn spring-boot:run
).
- When accessing a protected route (e.g.,
/user
), the application will redirect to Okta for authentication.
Frontend (Angular with Okta Authentication)
1. Set Up Okta for Angular
- Go to Okta Developer and create a new Single Page Application (SPA).
- Note down the Client ID, Issuer URL, and Redirect URIs (e.g.,
http://localhost:4200/callback
).
2. Install Okta SDK for Angular
Install the Okta Angular SDK:
3. Configure Okta in app.module.ts
In src/app/app.module.ts
, configure Okta settings:
4. Create an Auth Service
Create a service to manage login and logout:
5. Set Up the Callback Component
Create a callback.component.ts
to handle the OAuth2 callback and token storage:
6. Add Protected Routes
Set up routes in app-routing.module.ts
and protect them with OktaAuthGuard
:
7. Update HTML for Login and Logout
In app.component.html
, create UI elements for login/logout:
8. Run the Angular App
Ensure your Angular app is running (ng serve
).
- The redirect URI should be set correctly (e.g.,
http://localhost:4200/callback
). - After login, Okta will handle the OAuth2 flow, and the user will be authenticated in the backend (Spring Boot).
Final Steps:
- Test the flow: Start both your Spring Boot application and Angular frontend.
- Visit the Angular app (
http://localhost:4200
). - Click Login and Okta will authenticate the user.
- Upon success, you'll be redirected to the protected routes (e.g.,
/profile
). - Spring Boot will authorize the user based on the OAuth2 token provided by Okta.
- Visit the Angular app (