A Quick How-To Guide: Security with Spring Boot and Vaadin Fusion
When you build a web application, you’re working with many moving parts and pieces. Your frontend app is running business logic, the backend server deals with API calls, and it’s your job to make sure they’re secure and in sync. This article will teach you how to utilize Okta, Spring Boot, and Vaadin Fusion to create a full-stack web application with authentication. Specifically, this will involve: Creating a Spring Boot-based Vaadin Fusion app Securing server endpoints with Okta Using Okta Auth JS for logging in and securing Vaadin routes I worked with the Head of Community at Vaadin; Marcus Hellberg, who I met some time ago on the conference circuit. Both of us come from Finland, and hold Finnish roots; my grandparents built the sauna and cabin where I grew up, deep in Montana’s remote woods. Marcus and I also share the same compassion for web technologies and Java, with their capability to build fast and efficient applications. You might have noticed we refer to Vaadin as Vaadin Fusion—I had always thought of Vaadin as a web network based on Google’s GWT, but Marcus clarified there are now two products, one being Vaadin Flow, and the other being Vaadin Fusion. Vaadin Flow refers to the classic Vaadin server-side Java API, specifically designed as a new TypeScript font framework for Java backends. Both have full-stack type safety and use the same UI components. Vaadin is no longer based on GWT—its components, instead, use web component standards. Prerequisites Java 11+ Maven 3.6+ Table of Contents What Is Vaadin Fusion? Create a Spring Boot-based Vaadin Fusion Application Secure Your Spring Boot Backend Services Add the Okta Spring Boot Starter Register an OpenID Connect Application Configure Spring Security Create a Vaadin Endpoint for Accessing Data Call the Spring Boot Endpoint from Vaadin Fusion Start Your Vaadin + Spring Boot App Add a Vaadin Login Page and Restrict Access to Views Create an Auth Service for Authentication Create a Login View Restrict View Access to Authenticated Users Consume the Secure Endpoint from the Client Create a Middleware to Add the Access Token JWT to Server Requests Call the Secure Endpoint Methods Add a Logout Link Learn More About Vaadin and Spring Boot You can find the full completed source code for this tutorial on GitHub, in the oktadeveloper/okta-vaadin-fusion-spring-boot-example repository. What Is Vaadin Fusion? Vaadin Fusion is an open-source, front-end framework designed specifically for Java backends. Fusion gives you type-safe access to your backend from your client app by auto-generating TypeScript interfaces for your server Java objects. It wraps REST calls in async TypeScript methods, so you can access your backend as easily as calling any TypeScript function. End-to-end type checking means you catch any breaking changes at build time, not in production. Oh, and there’s auto-complete everywhere, so you can focus on coding, not reading API docs. Views are written in TypeScript with LitElement, a lightweight, reactive component library. Create a Spring Boot-based Vaadin Fusion Application Begin by creating a new Vaadin Fusion app with the Vaadin starter wizard. It allows you to configure views, tech stack, and theme before downloading an app starter. Rename the About view to "People" and change its URL to "people": Go into the application settings and change the name to Vaadin Okta. Then, select TypeScript + HTMLfor the UI stack to get a Fusion project. Click Download, and you’ll get a zip file containing a Maven project. Open the project in your IDE. The two important folders in the project are: /frontend - This folder contains all the frontend code /src/main/java - This folder includes all the backend code, which is a Spring Boot app Start the application with the following command: Shell x 1 mvn The launcher should open up the app in your default browser. If not, navigate to http://localhost:8080. Secure Your Spring Boot Backend Services Vaadin Fusion uses type-safe endpoints for server access. You create an endpoint by annotating a class with @Endpoint. This will export all the methods in the class and make them callable from TypeScript. Vaadin will also generate TypeScript interfaces for any data types the methods use. Vaadin endpoints require authentication by default. You can explicitly make an endpoint class or a single method accessible to unauthenticated users by adding an @AnonymousAllowed annotation. In this app, you want to restrict access to only authenticated users. You’ll use OpenID Connect (OIDC) and Okta to make this possible. Add the Okta Spring Boot Starter Add the Okta Spring Boot starter and Lombok dependencies to the section of your pom.xml file. XML xxxxxxxxxx 1 11 1 2 com.okta.spring 3 okta-spring-boot-starter 4 1.4.0 5 6 7 8 9 org.projectlombok 10 lombok 11 Make sure your IDE imports the dependencies, or re-run mvn. Register an OpenID Connect Application Create a free Okta developer account on developer.okta.com if you don’t already have one. Once logged in, go to Applications > Add Application and select Single-Page App. Configure the app settings and click Done to create the app: Name: Vaadin Fusion Base URIs: http://localhost:8080 Login redirect URIs: http://localhost:8080/callback Logout redirect URIs: http://localhost:8080 Grant type allowed: Authorization Code Store the issuer in src/main/resources/application.properties by adding the following property: Properties files xxxxxxxxxx 1 1 okta.oauth2.issuer=https://{yourOktaDomain}/oauth2/default Configure Spring Security Vaadin integrates with Spring Security to handle authorization. Instead of restricting access to specific routes as you would with Spring REST controllers, you need permit all traffic to /** so Vaadin can handle security. Vaadin is configured to: Serve index.html for the root path and any unmatched server route Serve static assets Handle authorization and cross-site request forgery (CSRF) protection in server endpoints By default, all server endpoints require an authenticated user. You can allow anonymous access to an endpoint or a method by adding an @AnonymousAllowed annotation. You can further restrict access by adding @RolesAllowed to an endpoint or a method. Create a new class SecurityConfiguration.java in the same package as Application.java with the following contents: Java xxxxxxxxxx 1 39 1 package com.example.application; 2 3 import com.okta.spring.boot.oauth.Okta; 4 5 import org.springframework.http.HttpMethod; 6 import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 import org.springframework.security.config.annotation.web.builders.WebSecurity; 8 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 9 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 10 11 @EnableWebSecurity 12 public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 13 14 @Override 15 public void configure(WebSecurity web) throws Exception { 16 // @formatter:off 17 web.ignoring() 18 .antMatchers(HttpMethod.OPTIONS, "/**") 19 .antMatchers("/**/*.{js,html,css,webmanifest}"); 20 // @formatter:on 21 } 22 23 @Override 24 protected void configure(HttpSecurity http) throws Exception { 25 // @formatter:off 26 // Vaadin handles CSRF for its endpoints 27 28 http.csrf().ignoringAntMatchers("/connect/**") 29 .and() 30 .authorizeRequests() 31 // allow access to everything, Vaadin will handle security 32 .antMatchers("/**").permitAll() 33 .and() 34 .oauth2ResourceServer().jwt(); 35 // @formatter:on 36 37 Okta.configureResourceServer401ResponseBody(http); 38 } 39 } Create a Vaadin Endpoint for Accessing Data Now that you have the server set up for authenticating requests add a service you can call from the client app. First, create a Person.java class to use as the data model in the com.example.application.views.people package. Java xxxxxxxxxx 1 11 1 package com.example.application.views.people; 2 3 import lombok.AllArgsConstructor; 4 import lombok.Data; 5 6 @Data 7 @AllArgsConstructor 8 public class Person { 9 private String firstName; 10 private String lastName; 11 } If you aren’t using Lombok, omit the annotations and add a constructor that takes in firstName and lastName, and create getters and setters for both. Open PeopleEndpoint.java and replace the contents with the following: Java xxxxxxxxxx 1 27 1 package com.example.application.views.people; 2 3 import com.vaadin.flow.server.connect.Endpoint; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 8 @Endpoint 9 public class PeopleEndpoint { 10 11 // We'll use a simple list to hold data 12 private List people = new ArrayList<>(); 13 14 public PeopleEndpoint() { 15 // Add one person so we can see that everything works 16 people.add(new Person("Jane", "Doe")); 17 } 18 19 public List getPeople() { 20 return people; 21 } 22 23 public Person adEclipsedPerson(Person person) { 24 people.add(person); 25 return person; 26 } 27 } Vaadin will make the getPeople() and addPerson() methods available as asynchronous TypeScript methods. It will also generate a TypeScript interface for Person, so you can access the same type-information of both on the server and in the client. Call the Spring Boot Endpoint from Vaadin Fusion Create a view that uses the server API. Open frontend/views/people/people-view.ts and replace its code with the following: TypeScript xxxxxxxxxx 1 83 1 import { 2 LitElement, 3 html, 4 css, 5 customElement, 6 internalProperty, 7 } from 'lit-element'; 8 import Person from '../../generated/com/example/application/views/people/Person'; 9 10 import '@vaadin/vaadin-text-field'; 11 import '@vaadin/vaadin-button'; 12 import { Binder, field } from '@vaadin/form'; 13 import PersonModel from '../../generated/com/example/application/views/people/PersonModel'; 14 import { addPerson, getPeople } from '../../generated/PeopleEndpoint'; 15 16 @customElement('people-view') 17 export class PeopleView extends LitElement { 18 @internalProperty() 19 private people: Person[] = []; 20 @internalProperty() 21 private message = ''; 22 23 // Manages form state, binds inputs to the model 24 private binder = new Binder(this, PersonModel); 25 26 render() { 27 const { model } = this.binder; 28 29 return html` 30 People 31 32 ${this.message} 33 34 35 ${this.people.map( 36 (person) => html`${person.firstName} ${person.lastName}` 37 )} 38 39 40 Add new person 41 42 46 50 Add 51 52 `; 53 } 54 55 async connectedCallback() { 56 super.connectedCallback(); 57 try { 58 this.people = await getPeople(); 59 } catch (e) { 60 this.message = `Failed to get people: ${e.message}.`; 61 } 62 } 63 64 async add() { 65 try { 66 const saved = await this.binder.submitTo(addPerson); 67 if (saved) { 68 this.people = [...this.people, saved]; 69 this.binder.clear(); 70 } 71 } catch (e) { 72 this.message = `Failed to save: ${e.message}.`; 73 } 74 } 75 76 static styles = css` 77 :host { 78 display: block; 79 padding: var(--lumo-space-m) var(--lumo-space-l); 80 } 81 `; 82 } Here’s what this code does: Defines two internal properties: people and message to hold the component’s state. Any time a property changes, the template will get re-rendered efficiently. Initialized a Binder for handling the new-person form. It keeps track of the model value, handles validations, and submits the value to the endpoint. The template: Lists all people in an unordered list () Displays a form for adding new people. The form uses two Vaadin components: vaadin-text-field and vaadin-button. The fields are bound to the Binder with the help of a spread operator (…=${field(…)}). You can read more about forms in the Vaadin documentation The Add button calls the add() method, which submits the form to the backend and adds the saved Person to the people array. If any of the server calls fail, message gets populated to inform the user. Start Your Vaadin + Spring Boot App Start the application with the following command: Shell xxxxxxxxxx 1 1 mvn You should now be able to launch the application and see the views. However, if you try to access the People page, you’ll get an error because you aren’t authenticated. You need to add a login view and authenticate the user before calling any of the secure endpoints. Add a Vaadin Login Page and Restrict Access to Views You are going to use a custom login screen and Okta Auth JS to authenticate users. You will do this in three steps: Create a service for handling everything auth related Create a login view Restrict view access to logged-in users and redirect unauthenticated users to the login view Create an Auth Service for Authentication Begin by installing the Okta Auth JS library with npm: Shell xxxxxxxxxx 1 1 npm i @okta/okta-auth-js@4.0.3 Then, create a new file, auth.ts, in the frontend folder. This is where all the authentication magic happens. TypeScript xxxxxxxxxx 1 64 1 import { AccessToken, OktaAuth } from '@okta/okta-auth-js'; 2 3 const authClient = new OktaAuth({ 4 issuer: 'https://{yourOktadomain}/oauth2/default', // use your own 5 clientId: '{frontend app client id}', // use your own 6 redirectUri: window.location.origin + '/callback', 7 pkce: true 8 }); 9 10 const isAuthenticated = async () => { 11 // Checks if there is a current accessToken in the TokenManger. 12 return !!(await authClient.tokenManager.get('accessToken')); 13 }; 14 15 const signIn = async (username: string, password: string) => { 16 const authResult = await authClient.signIn({ 17 username, 18 password, 19 scopes: ['openid', 'email', 'profile'], 20 }); 21 22 if (authResult.status === 'SUCCESS') { 23 authClient.token.getWithRedirect({ 24 sessionToken: authResult.sessionToken, 25 responseType: 'id_token', 26 }); 27 } 28 }; 29 30 const signOut = () => authClient.signOut(); 31 32 const handleAuthentication = async () => { 33 if (authClient.token.isLoginRedirect()) { 34 try { 35 const tokenResponse = await authClient.token.parseFromUrl(); 36 const {accessToken, idToken} = tokenResponse.tokens; 37 if (!accessToken || !idToken) return false; 38 39 authClient.tokenManager.add('accessToken', accessToken); 40 authClient.tokenManager.add('idToken', idToken); 41 return true; 42 } catch (err) { 43 console.warn(`authClient.token.parseFromUrl() errored: ${err}`); 44 return false; 45 } 46 } 47 return false; 48 }; 49 50 const getAccessToken = async () => { 51 const token = (await authClient.tokenManager.get( 52 'accessToken' 53 )) as AccessToken; 54 55 return token; 56 }; 57 58 export { 59 isAuthenticated, 60 signIn, 61 signOut, 62 handleAuthentication, 63 getAccessToken, 64 }; Here’s what auth.ts does: It creates an internal instance of AuthClient configured with your info It exports the following methods: isAuthenticated returns a boolean indicating whether or not the user is authenticated signIn takes a username and password and asks the client to authenticate. The client will redirect to the redirect URI handleAuthentication reads the response from the redirect and saves the returned tokens getAccessToken returns the access token for use with server calls signOut signs out the user Create a Login View Next, create a login view so users can enter their credentials and get authenticated. Create a new folder frontend/views/login. In that folder, create a new file login-view.ts with the following content: TypeScript x 1 import { customElement, html, internalProperty, LitElement } from 'lit-element'; 2 import { signIn } from '../../auth'; 3 import '@vaadin/vaadin-login/vaadin-login-form'; 4 5 @customElement('login-view') (1) 6 export class LoginView extends LitElement { 7 @internalProperty() 8 private error = !!new URLSearchParams().get('error'); 9 10 render() { 11 return html` 12 21 26 `; 27 } 28 29 async login(e: CustomEvent) { (4) 30 try { 31 await signIn(e.detail.username, e.detail.password); 32 } catch (e) { 33 this.error = true; 34 } 35 } 36 37 // Render in light DOM for password managers 38 protected createRenderRoot() { 39 return this; 40 } 41 } (1) The view uses LitElement to define a new component, . (2) Use the element for capturing login information. (3) The login-event is bound to the login method with @login=${this.login}. (4) The login() method calls the signIn() function in the auth service, which in turn will redirect the user to the callback URL. Restrict View Access to Authenticated Users The final piece of the puzzle is to add an authentication guard that only allows logged-in users to access the views. Any unauthenticated users should be redirected to the login page first. You also need to define logic for capturing the callback from Okta and logging out users. Open frontend/index.ts and replace its contents with the following: TypeScript xxxxxxxxxx 1 58 1 import { Commands, Context, Route, Router } from '@vaadin/router'; 2 3 import './views/main/main-view'; 4 import './views/login/login-view'; 5 import './views/helloworld/hello-world-view'; 6 import { handleAuthentication, isAuthenticated, signOut } from './auth'; 7 8 const authGuard = async (context: Context, commands: Commands) => { 9 if (!(await isAuthenticated())) { 10 // Save requested path 11 sessionStorage.setItem('login-redirect-path', context.pathname); 12 return commands.redirect('/login'); 13 } 14 return undefined; 15 }; 16 17 const routes: Route[] = [ 18 { path: '/login', component: 'login-view' }, 19 { 20 path: '/callback', 21 action: async (_: Context, commands: Commands) => { 22 if (await handleAuthentication()) { 23 return commands.redirect( 24 sessionStorage.getItem('login-redirect-path') || '/' 25 ); 26 } else { 27 return commands.redirect('/login?error'); 28 } 29 }, 30 }, 31 { 32 path: '/logout', 33 action: async (_: Context, commands: Commands) => { 34 signOut(); 35 location.reload(); 36 return commands.prevent(); 37 }, 38 }, 39 { 40 path: '', 41 component: 'main-view', 42 action: authGuard, // Require a logged in user to access 43 children: [ 44 { path: '', component: 'hello-world-view' }, 45 { path: 'hello', component: 'hello-world-view' }, 46 { 47 path: 'people', 48 component: 'people-view', 49 action: async () => { 50 await import('./views/people/people-view'); 51 }, 52 }, 53 ], 54 }, 55 ]; 56 57 export const router = new Router(document.querySelector('#outlet')); 58 router.setRoutes(routes); Here’s what this code does: authGuard is a Vaadin Router action that uses the auth service to check if a user is authenticated. If not, it will save the requested path and redirect to the login view In the router configuration, you added three routes: login maps to the login view component you created in the previous step callback handles the return value from Okta. If the authentication was successful, it will navigate to the path the user requested before being redirected to the login page logout signs out the user from the Okta Auth JS client and then destroys the Spring Security context by calling /logout on the server Adds the authGuard to main-view with action: authGuard Consume the Secure Endpoint from the Client One last thing we need to take care of before we can access the backend is to include the access token JWT with server requests. We can do this with a middleware. Create a Middleware to Add the Access Token JWT to Server Requests Create a new file, connect-client.ts in the frontend folder with the following content: TypeScript xxxxxxxxxx 1 27 1 import { 2 ConnectClient, 3 MiddlewareContext, 4 MiddlewareNext, 5 } from '@vaadin/flow-frontend/Connect'; 6 import { getAccessToken } from './auth'; 7 8 const client = new ConnectClient({ 9 prefix: 'connect', 10 middlewares: [ 11 async function addAuthHeaderMiddleware( 12 context: MiddlewareContext, 13 next: MiddlewareNext 14 ) { 15 const token = await getAccessToken(); 16 if (token) { 17 context.request.headers.set( 18 'Authorization', 19 `Bearer ${token.accessToken}` 20 ); 21 } 22 return next(context); 23 }, 24 ], 25 }); 26 27 export default client; The middleware uses the auth service to get the access token and adds it to the outgoing request headers. Call the Secure Endpoint Methods You are now ready to use the application. Run the application with the following command: Shell xxxxxxxxxx 1 1 mvn Once the application is up, go to http://localhost:8080, log in with the user you created. Once you are logged in, you should be able to view and add people through the secure server endpoint. Add a Logout Link Finally, add a logout link so users can sign out when they’re done. Open main-view.ts and add a link at the end of the section of the template, just after the Avatar image: HTML xxxxxxxxxx 1 1 2 3 ${this.getSelectedTabName(this.menuTabs)} 4 5 Log out 6 Add a margin to the link so that it doesn’t touch the edge of the screen in the styles section of main-view.ts: CSS xxxxxxxxxx 1 10 1 ... 2 header h1 { 3 font-size: var(--lumo-font-size-l); 4 margin: 0; 5 } 6 7 header .logout { 8 margin-right: 12px; 9 } 10 ... After making these changes, you should see a Log out link in the top right corner. Now you should be able to log in, add people, and log out. Huzzah! Learn More About Vaadin and Spring Boot We hope you’ve enjoyed this quick tutorial on how to integrate authentication with Okta into a Vaadin Fusion app. Now that you have a secure app up and running, you can start exploring other features of Vaadin and Okta. Here are some helpful resources to get started: Browse all Vaadin components Vaadin Fusion docs Okta developer docs You can find the full completed source code for this tutorial on GitHub in our okta-vaadin-fusion-spring-boot-example repository. If you want to know more about Spring Boot and Okta, you might find these blog posts helpful: OAuth 2.0 Java Guide: Secure Your App in 5 Minutes Build a CRUD Application with Kotlin and React How to GraphQL in Java Angular + Docker with a Big Hug from Spring Boot Easy Session Sharing in Spring Boot with Spring Session and MySQL Build a CRUD App with Vue.js, Spring Boot, and Kotlin As always, if you have any questions, feel free to leave us a comment below. Don’t forget to follow us on Twitter, like us on Facebook, check us out on LinkedIn, and subscribe to our YouTube channel.
December 9, 2020
by Matt Raible
·
4,761 Views
·
1 Like