Creating a clean, intuitive user interface is a key part of designing web applications. This has historically been challenging, however, because web apps don’t have a common design language like desktop apps do.

Enter Material Design. Google released Material Design in 2014 with the goal of creating a common user experience across Android devices and web apps. Material design has components that developers can use for both Android and JavaScript applications.

Material Design has become very popular. Developers have created libraries that incorporate Material Design components into existing frameworks. Within Angular applications, you can use the angular-material library, which makes all Material components available for your Angular templates. The catch is that you use Material Design in your application, you should be sure to use it across all parts of your app—it’s a common design language, after all. 

As you’re building your next app, you may want to use a single sign-on service like Okta. In its default configuration, Okta redirects users to a hosted login page and redirects them back to the app when they sign in successfully. If you’re using Material Design with your application, you might want to create your own login form to match the rest of your app, but you can still do this with Okta!

In this tutorial, I’ll show you how to create a login form like the one above. You’ll create an Angular app, use Material Design, and make it require user login. Okta provides a library specifically for Angular applications but I will be using the more low-level okta-auth-js library. This library allows you to have full control over your HTML and just handles communication with Okta’s API. All of Okta’s JavaScript libraries are built on top of okta-auth-js. To make the application a bit more interesting, I will be creating a small tic-tac-toe game that will be protected using Okta for authentication.

To get started, you will need to install the Angular command-line tool. I will assume that you have some familiarity with JavaScript and that you have Node installed on your system together with the Node Package Manager npm. Open a terminal and type the following command.

Depending on your operating system, you might have to run this using the sudo command. This will install the Angular command-line tool on your system. It lets you use the ng command to set up and manipulate Angular applications. To create a new application navigate to a directory of your choice and run the following.

You will be asked two questions. Answer Yes to the first question. This will include and set up the router in your application. The router is responsible for letting the user navigate between different parts of the app and updating the browser’s URL without actually reloading the page. For the second question, accept the default choice CSS. This application will use simple CSS stylesheets but you can see how easy it is to switch to a different stylesheet technology with Angular.

Once the wizard has completed you should see a new folder called material-tic-tac-toe. Navigate into the folder and install some packages you will need for the application by running the command below.

The @angular/material package provides the components of the Material Design, @angular/cdk is a component development kit that is needed for the Material components to work and hammerjs is a library that provides smooth animations for the component. @angular/flex-layout provides a flexible and responsive grid. It is independent of the Material components but is often used together with it. Finally, tic-tac-toe-minimax is a ready-to-go tic-tac-toe game with a computer player.

The Material components do not include the web-font for the Material Icon set. In order to use the icons, open src/index.html in your IDE and add the following line inside the <head> tag.

To make hammerjs available to the application open src/main.ts and add the following import to the top of the file.

Next, add the Material Design stylesheet to your application. Open src/styles.css and paste the code below into the file.

The @import statement imports a pre-built theme into the CSS file. I have also added a bit of styling for the body and h1 elements. Next, you need to import all the modules you will be needing into the application.

Open src/app/app.module.ts and add the imports below to the top of the file.

Now scroll down in the same file and find the imports declaration. Change it to match the following.

Now that you’re done with all the preliminaries, it’s time to start implementing the game application.

Start with the main application component. Open src/app/app.component.html and replace the default contents with the following code.

This code contains the main toolbar and menu of the application. Only a small amount of styling is needed. Paste the following into src/app/app.component.css.

Now, open src/app/app.component.ts and modify the component title and add an isAuthenticated property. The contents of the file should look like this.

Open your terminal again and create two components home, and game by running the commands below.

The home component simply contains a splash screen with the game title. Replace the contents of src/app/home/home.component.html with the following line.

The game component will need a bit more editing. Start with the template and open src/app/game/game.component.html. Replace the contents of the file with the following code.

The code above defined two cards. The top card contains the current game state. It also lets the user click on any of the fields to make a move. The bottom card contains the game controls. Add some styling by pasting the following code into src/app/game/game.component.css.

The actual game logic lives in src/app/game/game.component.ts. It is using the tic-tac-toe-minimax library to calculate computer moves and determine the winner. Replace the contents of the file with the code below.

To complete the game, you will need to define the routes to the two components.

Open src/app/app-routing.module.ts and add the following imports to the top of the file.

Next, change the routes array to match the following.

This completes the implementation of the game. You should now be able to open a terminal and run the following command:

Open your browser and navigate to http://localhost:4200. Click on the Play link in the top menu and you should see a fully functional tic-tac-toe game. Note that the Login link is not yet wired up. If you click on it nothing will happen and you can see an error message in the browser’s console.

Before you can start implementing the login page you need to register with Okta. Creating an account is simple and free. Just open a browser and navigate to https://developer.okta.com. Click Create Free Account and complete the registration process.

When you are done you will be redirected to your Okta developer dashboard. Register a new application by going to Applications > Add Application. On the next screen, choose Single Page App and click Next.

On the following screen, you can edit the application’s settings. Make sure that the port number is 4200 and the base URI is http://localhost:4200/. Change the Login Redirect URI to http://localhost:4200/login. Once you are done, you should now see a Client ID which you will need later in your code.

You will be implementing a login form as part of your application. Before continuing, a few warnings. If you decide to run a production environment in which you host your own login form, make sure that you are using the secure HTTPS protocol and you are hosting your site with a valid SSL certificate. Also, make sure to never store the login data in a session variable or the browser’s storage. If you fail to take the necessary security precautions, your site may be vulnerable to attacks. As mentioned above, you will not be using any of the Angular-specific Okta libraries. Instead, install the okta-auth-js package by opening the terminal in the project’s root folder and typing the following command.

With this, you are ready to create the authentication service. In the terminal, type the following command.

Now open the newly created file src/app/auth.service.ts. This file is where all the magic happens. Paste the following contents into the file. I will walk you through the code step-by-step below.

The AuthService defines a member authClient that is initialized to be an OktaAuth object. This object encapsulates the authentication, session management, and communication with the Okta servers. The OktaAuth constructor takes several options. The options provided here are the issuer and the clientId. In these options, you will have to replace {YourOktaDomain} with your Okta domain that you can find on the Okta dashboard. The {ClientId} needs to be replaced with the client ID you obtained when you registered your application with Okta.

The isAuthenticated property is a behavior subject that reflects whether the user is logged in or not. The AuthService also defines three asynchronous methods. The checkAuthenticated() method checks whether a user session exists and returns the outcome. It also updates the isAuthenticated subject. The login() method sends a sign-in request to the Okta server. On success, the user is authenticated and a session is established. The logout() method will sign out the user and redirect them to a specified route.

Now that the service is in place, you can use it in the application component. Open src/app/app.component.ts and modify the contents to match the code below.

The isAuthenticated variable is now initialized and updated by the authentication service. And the logout() method will sign the user out and redirect them to the home page.

Now create the login component. In the terminal, run the command below.

Open src/app/login/login.component.html and add the following login form.

Everything is contained in a <mat-card> element again. Note how the <mat-form-field> elements each contain an <input> as well as a <mat-error> element. The <mat-error> works seamlessly with Angular’s form validation to provide useful feedback. As you might have guessed by now, src/app/login/login.component.css contains some styling. Paste the code below into the file.

Now open src/app/login/login.component.ts and paste in the implementation of the login component.

There is not much happening here. ngOnInit() sets up the form. If the user is already authenticated it requests the router to navigate to a different URL. The onSubmit() function handles the form submission. It extracts the values from the form elements and attempts to log in using AuthService.

The application is almost done. You have the authentication service and the login form in place. But you also want to prevent the user from navigating to a part of the application that they are not authorized to see. Angular uses route guards for this. Create a new service by running the following command in the terminal.

The guard implements the CanActivate interface and must implement the canActivate() function. Replace the contents of src/app/auth-guard.service.ts with the following.

Finally, add the login route and the route guard to the router setup. Open src/app/app-routing.module.ts again and add the two imports below.

Now, change the routes array to look like the following.

Well done, that’s it. The application is complete!

When you run the ng serve command and navigate to http://localhost:4200 you should now be able to log in and out of the application. The login form uses Material Design and should look something like the image below.

Make Angular Tests Pass With Angular Material

You generated a lot of code in this tutorial. When you created components, tests were created for those components as well. The tests merely verify the components render. If you run ng test, most of them will fail because the tests don’t have the imports for the components you added. If you’d like to see what it takes to make all the tests pass, see this commit.

In this tutorial, I showed you how to implement your own login form in an Angular application using Material Design and the Angular Material library. Coding up your own form may be a viable option if you want to present a uniform user experience. Much of this tutorial can be used for other design libraries and is not limited to Material Design but Google’s Material Design standard is probably one of the most recognized user interface standards nowadays. Using it will improve the usability of your web application.

You can download the code for this tutorial from oktadeveloper/okta-angular-material-login-example.

If you want to learn more about Angular, Material Design, or ways to use Okta with Angular, feel free to check out the links below.

As usual, follow us @oktadev on Twitter and subscribe to our YouTube channel for more excellent content!





Source link

Write A Comment