Inside the body tag we have classes from materialize framework to add some background color. Update app.component.html as follows.
This router-outlet tag will be replaced with current component html as per router configuration.
In sign-up component, user registration form is enclosed inside card div from Materialize CSS(designed in previous article). Now let’s remove the card div and we will just keep the user registration form inside the html as follows.
First of all we have to design user component. Inside that we’ll add an outer div for both sign-in and sign-up components. For that I’ll add Materialize CSS card control with two tabs.
router-outlet inside this component will be replaced by either sign-in or sign-up component.
First of all create new file – routes.ts. Then use following rout configurations.
For sign-in and login path we have used one parent component (user component – for outer div) and inside the children we have Sign In and Sign Up component. With this file we have configured application routing, now we need to tell the application to follow these routes. Update app.module.ts file.
Now we can use this router path in user component tab control.
Here routerLinkActive is used to apply css class ‘active’, when we click on these anchor links.
Now let’s design the login form, Open and update the sign-in component html file as follows.
Here we have a template driven form. In-order to work this form, make sure that FormsModule is added to app.module.ts file. Both username and password text boxes are mandatory fields and hence required attribute is added to the inputs fields. Now we have a login form like this.
Now let’s update the Web API Project for Token Based Authentication. In-order to implement user authentication we need OWIN(Open Web Interface For .Net Applications). It act as a middle-ware between Asp.Net Application and IIS Server. First of all install required NuGet Packages.
In Solution explorer, Right Click On References. then click on Manage NuGet Packages. then do an online search for following packages and install them.
In-order to work with OWIN, we have to create OWIN Startup class. For that right click on Project > New Item, then Search for OWIN Startup class. and I’ll name the file as Startup.cs. Now you can update the class as follows.
Let’s discuss line by line.
app.UseCors function will enable CORS(Cross Origin Resource Sharing) inside the application. In previous article, we already enabled CORS in WebApiConfig.cs file. Now you can comment that line.
After Enabling CORS, we have an object of OAuthAuthorizationServerOptions. inside that we have following properties
Let’s create the ApplicationOAuthProvider provider class to validate username and password.
ApplicationOAuthProvider is inherited from OAuthAuthorizationServerProvider class. Inside that we have overridden two functions.
Now back to VS Code Editor. Let’s make token POST request on login form submission.
First of all create a function inside UserService class to make a token request as follows.
Along with userName and password you have to pass grant_type as password. With HttpHeader, we have set Content-Type as application/x-www-urlencoded. Additional No-Auth property is set to True. we can discuss need of this No-Auth property later.
Now open sign-in component html and then wire up a submit event
No let’s define the function inside the component typescript file.
Inside the OnSubmit() function, you have two arrow function, for success and error response. if user authentication is successful, we save the accessToken in localStorage (in web browser). because we need this token to authenticate the user in this angular 5. Finally we will navigate the user to home component.
If authentication is fails, isLogin is set to true, based on this property we will show an error message just above the login form.
Now let’s implement user authentication in this angular 5 project. First of all, I will create a new folder auth inside the app folder. Now lets create guard class for user authentication.
# from auth folder ng g g auth
So it will create auth.guard.ts file, inside that we’ll modify the canActivate() function as follows.
with canActivate() function we will check whether an user is authenticated or not using localStorage – userToken.
if not not authenticate we will send him to login form. in-order to work this guard we have to do some additional work.
open app.module.ts file, then add AuthGuard class inside providers array.
Now update routes.ts file by adding guard class to routes which is to be authenticated.
In this case, home route must authenticated so we have added canActivate array with AuthGuard class.
To consume Web API method with Authorize Attribute, we need to send access token along with the request. To demonstrate this process, let me add a Web API method with Authorize attribute.
Inside the Web API project, I’ll add a new Web API method inside AccountController as follows.
This method returns few user claims saved during user authentication. Now let’s call this Web API from Home Component. First of all update the home.component.html as follows.
Update the component typescript file.
Now let’s define the getUserClaims() function inside the UserService class.
So inside the home component ngOnInit Lifecyle-Hook, we consumed the GetUserClaims method and we have shown the result in home component html.
Here we didn’t append access token in the request, we can discuss that in a bit. We have a logout button in home component top Navbar. Logout() function is wired up to the logout button click event.
In UserService class function getUserClaims(), To consume the Web API method we have not appended the accessToken. It would be difficult to append accessToken to every Web API call and we have to handle the 401 UnAuthorized Response in each of them( if access token expires).
To do this task, we have a common place – HTTP Interceptor. For that I will create auth.interceptor.ts file in auth folder as follows.
Here AuthInterceptor class is inherited from HttpInterceptor class.
With the first IF statement, we will check the condition No-Auth is True/False. if it is true we don’t need to append the access token. So you can set No-Auth as true for web api calls which does not need authorization.
Then we check whether the user is authenticated or not. if authenticated then we will append the access token in request header. we must use the prefix Bearer while passing Authorization Access Token in request header. Inside the error function, we handle 401 Unauthorized Status Code – most often it can appear due to token expiration.
That’s it. Let me know your doubts and feedback in the comment box below. In the next part, we will discuss Role Based Authorization in Angular 5 with Web API.