未加星标

Authentication And Authorization In Angular - Part Twelve

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

Not often, but in most of the applications, we use authentication and authorization. In this article, we will explore the following topics.

JSON Web Tokens (JWT) Stateless Authentication How to Protect Routes in Angular Apps? Redirect the User to “Login” or “Access Denied” page. Show/Hide Elements Depending Upon the Authentication Status of the User How to Get Currently Logged In User? How to Consume Protected API Endpoints?

If you’ve not seen my Angular series yet, you should start your journey from here.

Introduction And Setting Up The Environment - Part One Typescript in a Nutshell - Part Two Building Blocks of Angular - Part Three Binding Variations And Displaying Data - Part Four Building Reusable Components Part Five Directives Part Six Template Driven Forms Part Seven Reactive Forms Part Eight CRUD Application with Fake HTTP Service Part Nine Handling Errors in Angular Part Ten Routing and Navigation Part Eleven Architecture

Before we get into the mechanics of implementing Authentication and Authorization, let’s have a quick look at high-level architecture. So, let’s start with Authentication.

In order to build authentication, on the client, we need to build the login page and on the server, we should build an API Endpoint to validate the user. When the user clicks on the login button, our Angular app calls this API Endpoint and passes the username and password. Now, on the server, we’re going to validate these credentials and if they are valid, we’re going to return what we called a JSON WEB TOKEN (JWT). This token is basically a JSjson object that includes certain attributes about the logged in user. And we use it to identify the user on the client and also on the server.


Authentication And Authorization In Angular - Part Twelve

Now we get these JSON WEB TOKEN objects on the Client and then we need to store it somewhere persistent, so it can exist across session restarts. So if the user closes your browser and then opens it again, the token still should be there and we use the localStorage for that. So almost all modern browsers have a simple storage per website and they also provide the API for storing key value pairs into this storage. So we’re going to use this native API to store our JSON Web Token inside the browsers’ local storage.


Authentication And Authorization In Angular - Part Twelve

Now on the client, we can use this token to identify the user. For example,

We can display their name on the navigation bar. We can show/hide parts of the page. We can prevent access to certain routes (if they don’t have the valid token).

This is how we work with these tokens on the client. Now let’s suppose, the user wants to get the list of orders from the server and this list is only available to an authenticated user. So, on the server, we have an API Endpoint (/api/orders) and in order to get the list of orders on the client, we should include the jwt in the request header. And then on the server, we should extract this token validated. And if it is valid it will return the list of orders otherwise it should return the unauthorized response. The response with the status code is 401.


Authentication And Authorization In Angular - Part Twelve

This is the big picture.

JSON Web Tokens (JWT)

Now let’s explore JWT in more detail. Look here we have a Debugger for working with JSON Web Tokens. Here, we also have a bunch of libraries to work with JSON web tokens. So as we already discussed we need to work with these tokens both on the client and on the server that’s why we have lots of libraries for different languages and platforms. So, on the front-end, we’ll use the library for Angular and for the backend we need a different library depending upon which platform or language you’re working in.

So, come to the Debugger tab in jwt.io where you see 2 tabs - Encoded & Decoded. So Encoded has a really long string of JSON web token.


Authentication And Authorization In Angular - Part Twelve

So, this is the token that the server has sent to the client upon successful authentication. Note the color coding here. This token has 3 parts. The header is indicated by red, the payload is indicated by purple, and the digital signature is indicated by blue. And we can see each of these parts on the decoded tab as well. One more thing - this token is not encrypted but encoded with BASE 64 algorithm. So, we don’t have any sensitive information here. If you paste this string into any Base 64 decoder, you can see the content.

Now, let’s come to the Decoded section.


Authentication And Authorization In Angular - Part Twelve

Here, we have the header which is basically a JSON object with 2 property algorithms, HS256 and type with JWT, this is the standard header. And we don’t have to be worry about it. Below that we have payload which is once again JSON object with a few properties, these properties are attributes about the user. So here we have sub for subject name and admin. This sub property identifies the subject of jwt which is the user's id and this object contains some content of the client. Now we can include a few other attributes here as well, a few other properties. And these are the properties we need to know in a lot of places in the application because we’re going to send this web token within the client and the server by including these properties in the token, we don’t have to go into the database to find let us say the name of the user everytime there is a request. So that’s why we have few basic properties of the user in the payload of the JSON web token. Now below that we have a signature, we use this signature to prevent a malicious user from modifying any of the header and payload properties. Because this signature is based on a secret that exists on the server.


Authentication And Authorization In Angular - Part Twelve

So unless your malicious user can compromise your server, it will not be able to generate the digital signature for a token.

Now let’s see how this digital signature is constructed. Basically we get the header encoded using base64 algorithm and concatenate it with payload encoded using base64. And then we use the secret to encrypt that long string using HMACSHA256 algorithm. So there are 2 interesting points here, first is this digital signature is based on the content of the JSON web token so if we change the payload the signature needs to be regenerated. In other words, a malicious user can’t come back here and simply modify any of the payload property for someone else JSON web token and if he modify any of the payload property he need to regenerate the digital signature. And the 2 nd interesting point here that this signature is generated through the secret that exists only on the server. So unless the hacker knows this secret, he can’t generate this digital signature.

Let’s see it in action. Let’s change the value of any payload property.


Authentication And Authorization In Angular - Part Twelve

Now look here the payload encoded string is also changed.


Authentication And Authorization In Angular - Part Twelve

So every time we modify the header or payload of the JSON web token, the signature is regenerated. Now we have the good understanding of high level architecture and JSON web token. Now let’s get started to implement authentication and authorization in our application.

Starter Code

So to speed things up, I’ve attached the starter code of “ Auth-Demo ” . So we’ll start authentication and authorization in this project. To configure this project to properly work, execute these commands one by one.

PS C:\Users\Ami Jan\auth-demo\auth-demo> npm install PS C:\Users\Ami Jan\auth-demo\auth-demo> npm i angular2-jwt --save PS C:\Users\Ami Jan\auth-demo\auth-demo> ng serve

Now when you run this application,


Authentication And Authorization In Angular - Part Twelve

This is what you get. If you go to Login, you’ll navigate to Login page but nothing gonna happen on sign in.


Authentication And Authorization In Angular - Part Twelve

So we’re getting this application and adding authentication and authorization into it. Before getting into the implementation details, let’s review few things of this project. So open app.module.ts. Look here in the imports array, we can see we have few routes.

imports:[ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot([ {path:'',component:HomeComponent}, {path:'admin',component:AdminComponent}, {path:'login',component:LoginComponent}, {path:'no-access',component:NoAccessComponent} ]) ]

Now look at the providers array,

providers:[ OrderService, AuthService, //Forcreatingamockback-end.Youdon'tneedtheseinarealapp. fakeBackendProvider, MockBackend, BaseRequestOptions ],

Here we have OrderService which is a very simple service getting the list of orders from the server. Next we have AuthService which we use to implement login and logout. Now let’s take a look of AuthService.

exportclassAuthService{ constructor(privatehttp:Http){ } login(credentials){ returnthis.http.post('/api/authenticate', JSON.stringify(credentials)); } logout(){ } isLoggedIn(){ returnfalse; } }

So it is the very simple class that is dependent upon the http service as you can see in class constructor. We’re injecting Http as the dependency to AuthService. Here we have the login() method which is kind of half implemented, which we’ll finish in this complete article. Here we have other methods as well (logout(), isLoggedIn()) and it looks like they are not implemented as well. Now back in app.module.ts, after AuthService we have few providers that are purely implementing mock backend. So you don’t need to add them in the real world application

//Forcreatingamockback-end.Youdon'tneedtheseinarealapp. fakeBackendProvider, MockBackend, BaseRequestOptions

Now let’s see how we implemented this mock backend. So let’s go to fakeBackendProvider

import{Http,BaseRequestOptions,Response,ResponseOptions,RequestMethod}from'@angular/http'; import{MockBackend,MockConnection}from'@angular/http/testing'; exportfunctionfakeBackendFactory( backend:MockBackend, options:BaseRequestOptions){ lettoken='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik1vc2ggSGFtZWRhbmkiLCJhZG1pbiI6dHJ1ZX0.iy8az1ZDe-_hS8GLDKsQKgPHvWpHl0zkQBqy1QIPOkA'; backend.connections.subscribe((connection:MockConnection)=>{ //WeareusingthesetTimeout()functiontosimulatean //asynchronouscalltotheserverthattakes1second. setTimeout(()=>{ // //Fakeimplementationof/api/authenticate // if(connection.request.url.endsWith('/api/authenticate')&& connection.request.method===RequestMethod.Post){ letbody=JSON.parse(connection.request.getBody()); if(body.email==='abc@domain.com'&&body.password==='1234'){ connection.mockRespond(newResponse( newResponseOptions({ status:200, body:{token:token} }))); }else{ connection.mockRespond(newResponse( newResponseOptions({status:200}) )); } } // //Fakeimplementationof/api/orders // if(connection.request.url.endsWith('/api/orders')&& connection.request.method===RequestMethod.Get){ if(connection.request.headers.get('Authorization')==='Bearer'+token){ connection.mockRespond(newResponse( newResponseOptions({status:200,body:[1,2,3]}) )); }else{ connection.mockRespond(newResponse( newResponseOptions({status:401}) )); } } },1000); }); returnnewHttp(backend,options); } exportletfakeBackendProvider={ provide:Http, useFactory:fakeBackendFactory, deps:[MockBackend,BaseRequestOptions] };

So here we have exported the function fakeBackendFactory, this function takes 2 parameters, MockBackend and BaseRequestOptions. Don’t be scared by watching the above code, always write the simple code. It doesn't need to be more complex. The above code is just for demonstration.

So here we have declared a variable token and we have set this to a valid JSON web token that extracted from a jwt.io and if you see the comment ‘Fake implementation of /api/authenticate’ in the code. So here we have some basic logic to check the url of the request.

if(connection.request.url.endsWith('/api/authenticate')&& connection.request.method===RequestMethod.Post){ }

So if the url of the request ends with /api/authenticate and the request method is post, that means the client sends the http post request to this endpoint. Here we want to validate the username and password and if they are valid, it will return jwt

if(body.email==='abc@domain.com'&&body.password==='1234'){ connection.mockRespond(newResponse( newResponseOptions({ status:200, body:{token:token} }))); }else{ connection.mockRespond(newResponse( newResponseOptions({status:200}) )); } In else block the

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Authentication And Authorization In Angular - Part Twelve
本站链接:https://www.codesec.net/view/611409.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(43)