Security is the main feature of any application, we will use in this article Web API 2 bearer token, created through Owin oAuth, which we created in our previous article. Pass Bearer token with every HttpRequest with the help of HttpInterceptor. In this article we will see only the authentication and guard the pages. We will implement refresh token in next article because might be you are here only to know how to refresh token and retry the failed request.

Create a new Angular CLI application, let it install all the dependencies and check whether it is working properly.

Auth.Service.ts

Create a new folder "shared" inside the app folder to keep our services. Create new service in shared folder say auth.service.ts. Let's analyze what this auth service will have in it:

a method login to call the service to validate credential and create token

a method getUserDetail to get the user detail from sessionStorage

a method logout to clean everything from sessionStorage and redirect user to the login page.

a method to refresh the token when we will get 401 - unauthorized error

a getter to check user is logged in or not isLoggedIn

a getter to get the value of token getToken

a getter to get the value of refresh token getRefreshToken

a method manageSession to manage the token, refresh token and user detail on sessionStorage

We will also need some extra information say previous page Url so we can redirect to that page after successful login. A way to indicate other pages/components that user is logged in so time to refresh the menu and any other activity like start timer for idle timeout etc.

redirectUrl: string; to keep previous page url

loginStatus: EventEmitter<boolean> = new EventEmitter<boolean>(); so we can indicate login/logout status

So let's see everything one by one and then complete code together, first we see the constructor and login method

Logout method to remove the sessionStorage data. First we copy the current URL to the variable, so we can redirect to the page once user login again. remove some values from sessionStorage, redirect to the login page and emit (broadcast) that user is logged out, if you are listening it, do whatever you have to do like change menu etc. we will see latter with navbar component:

Auth.Guard.ts

We completed our authentication service, now let's create the simplest file call auth guard which will protect the route to access if user will not have proper authorization whether it's a role or authentication. Create a new file inside the shared folder where we created our Auth Service and give a name auth.guard.ts and add following code in it:

Note we implemented CanActivate interface which will return boolean, whether user is logged in or not.

We used a method to check the user is logged in or not named checkLogin, if user is logged in return true otherwise set current url for future and move to login page and return true.

App-Routing.Module.ts

We completed our authentication service and authentication guard, time to create the routing for entire application, we are going to use normal routing rather than lazy loading, if you are interested about lazy loading see my article Angular 6 Lazy Loading with demo. Create a new module named AppRouting.Module.ts and add following code to protect our secured pages except the login page:

Note we are importing our app-routing and both auth service and auth guard in providers.

Tokenized-Interceptor

To add authentication token with every HTTP request after login we will use an interceptor which is introduced after Angular 4.3.1, luckily we are using Angular 6 so we can benefit from this feature. Create a new file called Tokenized-Interceptor.ts on the root. We will implement HttpInterceptor in this class. Le't see how we can add a header with any request, create function in it with name addHeaders like this:

Don't be panic, bear with me, I will provide the complete code for this error handling in next article.

Let's create some components, so we can use the routing, gaurd, navbar etc. We are creating a project which is entirely protected and will only be allowed to authenticated users, so let's create

Login

Home

Customer

Product

Navbar

You can add any content on home, customer and product page and call a service from Web API so we can test by passing the token and try to get the values, even you can return a string from the Web API, and add Authorize attribute to them.

Login.Component.ts

Create a new component named login. What features we are going to achieve, let's see as a list:

Textbox for user id - Required

Textbox for password - Required

Login Button to login

Show required error on submit if value not provided

Show error for invalid id/password

remove error once user focused to any textbox

We are going to use the reactive form, it is not very complicated so I am going to copy the complete TypeScript code of LoginComponent:

I am not going to add the code for customer and product page, you can add the code in them and try to call any authorized method from Web API service and will see every time it will add a header to the request.

CORS error need to be fixed in Web API otherwise we will get error, so add following in you Web API Config file:

These errors will occur only on development machine so you can remove them before moving to production server.

I don't thing you need the navbar code but let me add that might be it can help someone. Because we need to change the menu and consume the logout and emitter used in Authentication Service to indicate whether use is logged in or logged out. Create a new component called navbar and copy following code in it:

That's it for the Authentication, Authorization and passing token to the Web API with the help of HttpInterceptor and handling basic errors.

Soon we will see the code for Refresh Token and how to handle the failed request after refreshing the token.

If you are looking for the code for this article, sure I will upload on Github after next article, adding the refresh token and retry pending request.

Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.

Other blogs you may like

Angular 4.3.1 introduced HttpInterceptor, we will use HttpClient and new HttpInterceptor feature to handle error globally for entire application.
When calling the service method, we might get some kind of server error. It can be any kind, like poor network connection to reach to the server,...
By Ali Adravi
On 10 Aug 2018
Viewed: 5,223

Token base authentication expires over a fixed time, to overcome on it we need to use the refresh token. We will try to create the token as well as the refresh token after successful login, refresh token will be used to generate a new token if current token is already expired and it is not too...
By Ali Adravi
On 08 Oct 2018
Viewed: 466

Create Token with user credential & roles and authorize action methods based on role in Web API is the topic we will cover in this article. We would need to pass token in every request and decorate action methods with [Authorize(Roles = "Admin, Manager") etc. that's only the code we will need to...
By Ali Adravi
On 04 Oct 2018
Viewed: 511

Have you recently created a web application using Visual Studio 2015RC? Looking to integrate Facebook authentication to this web application built on ASP.Net5? Then you have hit the right keys and reached the right place. Here, you will use easy steps to integrate Facebook authentication.
Now,...
By Deepa Ranganathan
On 19 Jun 2015
Viewed: 325