Let’s add a beautiful login form and user profile in the previous MEAN Stack Project, Inside that we already implemented JWT Authentication in Back-end Node JS API.
GitHub link up-to this article : https://goo.gl/GVBRPo.
So far we have discussed following related topics in MEAN Stack:
- CRUD Operation – Insert Update View and Delete.
- User Registration
Node JS Back End.
Angular 6 Front End.
- JWT User Authentication
Node JS Back End.
Angular 6 Front End( this one).
First of all, I’ll update default style sheet – styles.css as follows.
One more thing, I want to add a top image for previous user registration form. so first add an image user.png inside assets/img folder. then add an additional div for this image in sign-up.component.html as follows.
Now user registration form will look like this.
Here is the final application structure.
as per the structure we have to create two components, one gaurd file and one interceptor.for that you can use following commands.
we’ll create the interceptor file later.
let’s update existing routes file for signIn and userProfile components.
that’s what we needed for this application.
Now let’s design two tabs in user.component.html – one for login form and one for user registration form. so let’s update user.component.html.
routerLink set href attribute for anchor element. routerLinkActive apply css class ‘active’ when current url is same as anchor href.
Design Login Form
update signIn.component.ts with following properties, we need them for designing login form.
Now let’s update corresponding html file.
top div image is there in img folder. simple form validation is implemented as we have seen in previous user registration tutorial. error div will display error message stored inside the property (serverErrorMessages), after form submit event.
Now our login form look like this.
Now let’s implement the submit event by defining the function – onSubmit inside component Typescript file.
UserService class function login is to be defined, inside that we make post request to ‘/authenticate’ from Node JS API by passing email and password.
Inside the success callback function, we save jwt inside local storage with key – ‘token’ ( setToken function is to be defined in service class) and the userProfile component will be shown. Error callback will store the error message in serverErrorMessage property.
Now let’s update UserService class with new functions.
along with setToken function we have functions for reading and deleting jwt token from Local Storage.
Inside the signIn component, we have created an object of UserService class, as part of service class injection in app.module.ts file. so you have to remove the service class from signUp component providers array( added during user registration form design). Now add them in app.model.ts file as follows.
Secure Private Routes
After successful authentication, userProfile component will be shown, But I can directly access the same userProfile without authentication by editing URL. So let’s block such type of unauthorized request. for that we use guards from Angular, we have created a guard – auth.guard.ts. so we’ll update the file as follows.
Inside this guard function – canActivate, we just need to define the criteria to check whether a user is logged in or not. For that we have called isLoggedIn fuction ( which is to be defined). If not logged in, we re-direct the user to login page, delete his token and return false. Otherwise it return true. Before using the guard, we have to define isLoggedIn function in service class as follows.
getUserPayload function will return information stored in jwt payload, if there is no token it returns false. Inside isLoggedIn function we call getUserPayload, if there is token it will check for token expiration using exp claim.
Now we need to use AuthGuard class in routes.ts file. Before that we have add guard class in app.module.ts file.
Now protect userprofile route in routes.ts using this AuthGuard class. so update userprofile route in routes.ts file as follows.
Implement User Profile
Inside user profile component I want to show the details of logged in user. so first of all define getUserProfile function in UserService class as follows.
We implemented this ‘/userprofile’ as a private route in Node JS, so we have to send jwt token in request header. Before that let’s design the component. so we can update user-profile.component.ts as follows.
Inside ngOnInit lifecycle hook, user details send from the API is stored in userDetails property. You can predict what is happening inside onLogout function. So let’s use these in component html file.
With these, userProfile component will look like this.
Add JWT to Request Header Using HttpInterceptor
Now let’s add JWT into request header, for that we use HttpInterceptor. so first of all create the auth.interceptor.ts as follows.
Here we have this AuthInterceptor class which implements HttpInterceptor Interface. So we must define the function intercept. From now onwards all request from the application will go through this function. Hence all common function can be done inside the function, Here we are going to add JWT token into request header for request which doesn’t have noauth in their header. noauth property will be set to true for request which doesn’t demand authorization. such request will be send to API without making any change. so that’s why we called next function directly.
Else we set JWT in Authorization header and then we make the request. Inside tap-error callback function, we will redirect the user to login page.
Add this new interceptor into app.module.ts.
Now we have to update all API call with noauth property in service class, which does not need authentication.
Finally if you want to redirect the user to user profile when authorized user access login page. You can update the sign in component ngOnInit lifecycle hook as follows.
Step by Step Video Tutorial