Example of using a JWT authentication method in Angular

This article introduces the use of JWT authentication method examples in Angular, share it to everyone, the specific:

在Angular中使用JWT认证方法示例

Project address: grading-system

based on Session’s certification and way to TOKEN-based authentication have been widely used. In session authentication, the server stores a user login message. This login information will pass to the browser when responding and saved as cookies. When the next request, this login information will be identified, so that the request can be identified. Which user comes from.

In the session-based authentication, each user must generate a session. This session is usually saved in memory. As the number of users increases, the overhead of the server increases, and the distributed Applications are not very friendly.

In TOKEN authentication, the server does not need to retain user authentication information. When the user logs in, the server will return token after verifying the user information. This token is stored on the client and putting this token in each requested request header, so that the server can return data.

JWT (JSON Web token) is an open standard (RFC 7519) defining a compact and independent manner, which can be securely transmitted securely between the parties as a JSON object. This information can be verified and trust through digital signatures. It is especially suitable for single sign-on (SSO) scenarios for distributed sites.

What is jwt, why do you want to use JWT?

JWT is the abbreviation of JSON Web tokens, the most streamlined answer for this problem is that JWT is simple, compact, safe, specific to: Simple : As long as the user logs in, only one HTTP Header authentication information is required to use JWT certification, which can be simply implemented in a function, we will see this in the following example.

Compact: JWT TOKEn is a Base 64 encoded string that contains several headers and some necessary data, very simple. The JWT string after the signature is usually no more than 200 bytes.

Security: JWT can encrypt using the RSA or HMAC encryption algorithm to ensure that TOKEN is effective and preventing tampering.


In short, you can have a safe and effective way to authenticate users, and authenticate all APIs without analyzing complex data structures or implementing their own encryption algorithms.

JWT constitutes

JWT consists of three parts separated by
.

, they are:

head HEADER

Signature

That is, JWT is just a string having the following format:
  • Header.PayLoad.Signature
  • Head
  • Head is usually Two parts composition: Type of tokens (i.e., JWT) and a hash algorithm being used, such as HMAC SHA256 or RSA.

Header.PayLoad.Signature

 Then, the base64 encoded is performed to form a first portion of JWT.   
ewogicjhbgcioiaisfmyntyilaogicj0exaioiaislduigp9

Load

The second part of JWT is a load, which contains a statement. The statement is a statement about entities (usually users) and other data. There are three statements: registration declarations, open statements and private statements.

JWT specification defines seven declaration names registered in standard, they are:
 ISS: JWT issuer   Sub: JWT 
AUD: Receive one party of JWT

Exp: JWT expiration time, this expiration time must be greater than the issuance of issuance

NBF: Before what time is defined, the JWT is Is not available.
 IAT: JWT issuance   JTI: JWT's unique identity, mainly used as a disposable token, thereby avoiding playback attack. 
For a particular situation, a public declaration name can be used. These include:

Auth_time: Time to occur

ACR: Certified context class reference

NONCE: Used to associate client session with ID token Value

    Finally, there is a private declaration name that can be used to communicate information related to identity, such as names or departments.
  • Due to public and private statements unregistered, please pay attention to avoid name conflicts.
  • For example, we define a PalyLoad:
  • {“SUB”: “1234567890”, “Name”: “TC9011”, “Admin”: True , “EXP”: 1441594722}
  • Then the Base64 encrypted, obtaining the second part of JWT:
  • EwogicjzdwIiOiAiMTIzNDU2Nzg5MCIsCiAgIm5hbWUiOiAidGM5MDExIiwKICAiYWRtaW4iOiB0cnVlLAogICJleHAiOiAxNDQxNTk0NzIyCn0 =
Signature

    signed by the head base64 encoding, and loads the base64 encoded secret composition.
  • For example, both the two encoded strings will be used in the following sentence number
  • .
  • is connected (head before), it is formed:
ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIgp9.ewogICJzdWIiOiAiMTIzNDU2Nzg5MCIsCiAgIm5hbWUiOiAidGM5MDExIiwKICAiYWRtaW4iOiB0cnVlLAogICJleHAiOiAxNDQxNTk0NzIyCn0 =

then, the upper splicing finished string secret as a secret key for encrypting HS256.

HMACSHA256 (Base64urlencode (HEADER) + “.” + Base64urlencode (payload), Secret)

   Using JWT 
Generally, in the request header

Authorization

, and
bearer

is labeled:

Fetch (‘API / V1 / User / 1’, {Headers: {‘Authorization’: ‘BEARER ‘+ TOKEN}}

The server will verify token if verification will return the corresponding resources. However, pay attention, because the load is Base64 encoding, this coding can be symmetrically decrypted, so the user’s sensitive information should not be stored, such as a password. So general JWT is used to deliver some non-sensitive information to the web, such as user name, department, etc.

Use JWT

Here we use Angular6 and KOA2 (using TypeScript) to introduce how to use JWT in your Angular application.

Service

First in the JWT.IO official website to find Node’s JWT library: JSonWebtoken.
   You can see that the official website puts this library to support the standard registration statement field and the support of encryption methods. In addition to this library, you also need to use a middleware of the KOA: KOA-JWT to perform JWT authentication for HTTP requests. You can install these two libraries through the following command: 

NPM I Koa-jwt jsonwebtoken –save

In app.ts :

Import * AS JWT from ‘Koa-jwt’; app.use (jwt ({secret: secret}) .unless ({PATH: [/ \ / / / login /, / \ /, \],});

在Angular中使用JWT认证方法示例

Here the second is you The secret key defined by your own,
 Unless  method is used to exclude some APIs that do not require JWT certification. The KOA-JWT middleware needs to be checked for all routing (except  unsS 
set in UnsS
) before the routing middleware. Only the correct access can be accessed.

In addition, you have to customize the middleware of a 401 error handling, if there is no token, or token invalid, the middleware gives the corresponding error message. If there is no custom middleware, the error information exposed directly

KOA-JWT

directly returns to the user.

Export const ErrorHandle = (CTX, Next) => {Return next (). Catch ((err) => {if (err.status === 401) {ctx.status = 401; HandleError ({CTX, Message: ‘login expired, login’, err: err.originalError? err.originalError.MESSAGE: Err.Message});} else {throw err;}})

Then before the middle member is placed before KOA-JWT:

在Angular中使用JWT认证方法示例 App.use (ErrorHandle ); app.use (jwt ({secret: secret}). unless ({path: [/ \ / / \ \, / \ / login /, / \ / groups /],}));

When the user logs in, generate token, return to the client:
  / / Generate token returns to the client const token = jsonwebtoken.sign ({User: {Worknumber: user.worknumber, realname: user.realname, group: user.group, role : user.role}, // Setting Token Expired Time Exp: Math.Floor (Date.Now () / 1000) + (60 * 60 * 24), // 1 Day}, Secret); Handlesuccess ({CTX, Message : 'Landing success!', Response: {token, lifetime: Math.Floor (Date.Now () / 1000) + (60 * 60 * 24) // 1 day}}); 

It should be noted that when jsonwebtoken.sign ()

needs to be incomed
Secret parameters,
 Secret  must To match  Secret 
in the previous setting JWT ()
.

In Angular, we need to use @ Auth0 / Angular2-jwt this library to help us handle JWT:

in Angular npm install @ auth0 / angural-jwt –save

 APP jwtmodule  in .Module.ts 
(note that the introduction of the module also introduces httpclientmodule
module):

 import {JwtModule} from '@ auth0 / angular-jwt'; import {HttpClientModule} from '@ angular / common / http'; export function tokenGetter () {return localStorage.getItem ( 'token');} @ NgModule ({bootstrap: [AppComponent], imports: [// ... HttpClientModule, JwtModule.forRoot ({config: {tokenGetter: tokenGetter, whitelistedDomains: [ 'localhost: 3001'], blacklistedRoutes: [ 'localhost: 3001 / auth / ']}})]}) export class appmodule {}   In 
jwtmodule in
Config

:

tokengetter : Get the Token;
  : WhitelistedDomains 
: Allows the domain name of the authenticated request;

BlackListedRoutes :You don't want to replace the API list of Authorization information in HEADER. Then create a global Auth.Service.ts service, which is convenient to obtain user-related information and permissions when landing, there is a login method in this service, Used to process the token information returned after login, save the Token to LocalStorage, so before the TOKEN failed, the next user will not need to enter the username and password:

Login (LoginInfo: LoginInfo): Observable

{Return this.passportService.postLogin (LoginInfo) .pipe (map ((res: loginres) => {// After successful, get token, and save to LocalStorage this.StoRageService .setLocalStorage ( ‘token’, res.token); const decodedUser = this.decodeUserFromToken (res.token); this.setCurrentUser (decodedUser); this.msg.success ( ‘successful login!’); return this.loggedIn;} (}

In this login
 method,  decodeUserFromToken  encapsulated 
@ auth0 / angular2-jwt [ 1 DecodeToken
method provided in 23], pay attention to

DecodeToken method is based on the server jsonwebtoken.sign () , it is required to pass Operation acquisition User

:
User :
   
DECodeUserFromToken (Token): User {Return this.jwthelperService.Decodetoken (token) .user;}

In this service, two variables are defined loggedin and Isadmin

, is used to identify if the user is logged in and its corresponding permissions, which is convenient to control the view that can be accessed in Angular routing.

There are of course login, of course, there is also logout, just remove Token from localStorage and reset several variables:

Logout (): void {this.StrageService.removeLocalStorage (‘token’); this.loggedin = false; this.currentuse = false; this.currentuser = new user ();}

AUTHSERVICE is as follows:

Import {INJECTABLE, INJECTOR} from '@angular / core '; import {Router} from' @ angular / router '; import {JwtHelperService} from' @ auth0 / angular-jwt '; import {Observable} from' rxjs'; import {map} from 'rxjs / operators' Import {loginInfo, loginres, user} from '../../views/passport/interfaces/passport'; IMPORT {PassportService} from' ../../views/passport/services/passport.service'; IMPORT.SERVICE'A etc {StorageService} from '../storage/storage.service';import {NzMessageService} from' ng-zorro-antd '; @ Injectable () export class AuthService {public loggedIn = false; public isAdmin = false; public currentUser: User = New User (); Constructor (Private JwthelperService: JWTHELPERSERVICE: JWTHELPERSERVICE, PRIVATE ROTER: ROUTER, Private Injector: Injector, Private PassportService: PassportService, Private StorageService: PRIVAGERVICE:StorageService) {const token = localStorage.getItem ( 'token'); if (token) {const decodedUser = this.decodeUserFromToken (token); this.setCurrentUser (decodedUser);}} get msg (): NzMessageService {return this.injector .get (NzMessageService);} login (loginInfo: LoginInfo): Observable {return this.passportService.postLogin (loginInfo) .pipe (map ((res: LoginRes) => {this.storageService.setLocalStorage ( ‘token’ , RES.TOKEN; const decodeduser = this.decodeUserFromToken (res. Token); this.setCurrentuser (DECODEDUSER); this.msg.success (‘login success!’); return this.loggedin;});} logout : void {this.StorageService.RemovelStorage (‘token’); this.loggedin = false; this.curs = false; this.currentuser = new user ();} DECODEUserFromToken (token): User {return this.jwtHelperService.decodeToken (token) .user;} setCurrentUser (decodedUser): void {this.loggedIn = true; this.currentUser.workNumber = decodedUser.workNumber; this.currentUser.realName = decodedUser .realname; this.currentuser.group = decodeduser.group; this.currentuser.Role = decodeduser.role; this.isadmin = decodeduser.Role> 10; delete decoduser.role;}}

  At this point, JWT certification is introduced in your Angular application. Of course, you can also use  @ auth0 / angular2-jwt , handwritten an HTTP interceptor, manually set each time Request HEADER: 
@Injectable () Export Class Authinterceptor Implements Httpinterceptor {Intercept (Req: httprequest

, next: httphandler): Observable > {Const Token = localStorage.getItem ("token"); if (token) {Const cloned = Req.clone ({headers: Req.Headers.set ("Authorization", "+ token)}; Return next.handle (cloned);} else {return next.handle (REQ);}} } However, the Token Base64 decoding also needs to handwick itself, a little troublesome. Summary JWT Because it is based on JSON, it is very versatile, and many languages ​​have a JWT-related library. However, when using JWT, you need to pay attention to the following: Save the Secret Secret Key, this secret can only exist in the server to set a expiration time, because once Token is generated, it is always valid, unless the token key is changed or expired can only store some of the non-sensitive information necessary for some business logic

or more All content, I hope to help everyone, I hope everyone will support Tumi Clouds.
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment