1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 1x 1x 1x 1x 24x 10x 24x 24x 30x 2x 2x 28x 26x 26x 2x 2x 2x 2x 1x 1x 1x 1x 2x 24x 24x 24x 24x 24x 24x 66x 5x 61x 24x 2x 2x 2x 1x 1x 1x 1x 4x 4x 4x 4x 2x 2x 2x 2x 4x 1x 1x 1x 1x | /** * @module Authentication * @preferred * @description This module that contains authentication-related classes, types and interfaces */ /** */ import { LoginState, LoginResponse, RefreshResponse, Token, TokenStore, IAuthenticationService, TokenPersist } from './'; import { Subject, BehaviorSubject, Observable } from '@reactivex/rxjs'; import { BaseHttpProvider } from '../HttpProviders/BaseHttpProvider'; import { ODataHelper } from '../SN'; /** * This service class manages the JWT authentication, the session and the current login state. */ export class JwtService implements IAuthenticationService { /** * This subject indicates the current state of the service * @default LoginState.Pending */ public get State(): Observable<LoginState>{ return this.stateSubject.asObservable(); } /** * Gets the current state of the service * @default LoginState.Pending */ public get CurrentState(): LoginState{ return this.stateSubject.getValue(); } private readonly stateSubject: BehaviorSubject<LoginState> = new BehaviorSubject<LoginState>(LoginState.Pending); /** * The store for JWT tokens */ private TokenStore: TokenStore = new TokenStore(this.repositoryUrl, this.tokenTemplate, (this.persist === 'session') ? TokenPersist.Session : TokenPersist.Expiration); /** * Executed before each Ajax call. If the access token has been expired, but the refresh token is still valid, it triggers the token refreshing call * @returns {Observable<boolean>} An observable with a variable that indicates if there was a refresh triggered. */ public CheckForUpdate(): Observable<boolean> { if (this.TokenStore.AccessToken.IsValid()){ this.stateSubject.next(LoginState.Authenticated); return Observable.from([false]); } if (!this.TokenStore.RefreshToken.IsValid()) { this.stateSubject.next(LoginState.Unauthenticated); return Observable.from([false]); } this.stateSubject.next(LoginState.Pending); return this.ExecTokenRefresh(); } /** * Executes the token refresh call. Refresh the token in the Token Store and in the Service, updates the HttpService header * @returns {Observable<boolean>} An observable that will be completed with true on a succesfull refresh */ private ExecTokenRefresh() { let refresh = this.httpProviderRef.Ajax(RefreshResponse, { method: 'POST', url: ODataHelper.joinPaths(this.repositoryUrl, 'sn-token/refresh'), headers: { 'X-Refresh-Data': this.TokenStore.RefreshToken.toString(), 'X-Authentication-Type': 'Token' } }); refresh.subscribe(response => { this.TokenStore.AccessToken = Token.FromHeadAndPayload(response.access); this.stateSubject.next(LoginState.Authenticated); }, err => { console.warn(`There was an error during token refresh: ${err}`); this.stateSubject.next(LoginState.Unauthenticated); }); return refresh.map(response => { return true }); } /** * @param {BaseHttpProvider} httpProviderRef The Http Provider to use (e.g. login / logout / session renew requests) * @param {string} repositoryUrl The URL for the repository * @param {string} tokenTemplate The template to use when generating token keys in session/local storage or in a cookie. ${siteName} and ${tokenName} will be replaced. * @param {'session' | 'expiration'} persist Sets up if the tokens should be persisted per session (browser close) or per token expiration (based on the token) * @constructs JwtService */ constructor(private readonly httpProviderRef: BaseHttpProvider, private readonly repositoryUrl: string, private readonly tokenTemplate: string, public readonly persist: 'session' | 'expiration') { this.stateSubject = new BehaviorSubject<LoginState>(LoginState.Pending); this.State.subscribe((s) => { if (this.TokenStore.AccessToken.IsValid()){ this.httpProviderRef.SetGlobalHeader('X-Access-Data', this.TokenStore.AccessToken.toString()); } else { this.httpProviderRef.UnsetGlobalHeader('X-Access-Data'); } }); this.CheckForUpdate(); } private handleAuthenticationResponse(response: LoginResponse): boolean { this.TokenStore.AccessToken = Token.FromHeadAndPayload(response.access); this.TokenStore.RefreshToken = Token.FromHeadAndPayload(response.refresh); if (this.TokenStore.AccessToken.IsValid()) { this.stateSubject.next(LoginState.Authenticated); return true; } this.stateSubject.next(LoginState.Unauthenticated); return false; } /** * It is possible to send authentication requests using this action. You provide the username and password and will get the User object as the response if the login operation was * successful or HTTP 403 Forbidden message if it wasn’t. If the username does not contain a domain prefix, the configured default domain will be used. After you logged in the user successfully, * you will receive a standard ASP.NET auth cookie which will make sure that your subsequent requests will be authorized correctly. * * The username and password is sent in clear text, always send these kinds of requests through HTTPS. * @param username {string} Name of the user. * @param password {string} Password of the user. * @returns {Observable} Returns an RxJS observable that you can subscribe of in your code. * ``` * let userLogin = service.Login('alba', 'alba'); * userLogin.subscribe({ * next: response => { * console.log('Login success', response); * }, * error: error => console.error('something wrong occurred: ' + error.responseJSON.error.message.value), * complete: () => console.log('done'), * }); * ``` */ public Login(username: string, password: string) { let sub = new Subject<boolean>(); this.stateSubject.next(LoginState.Pending); let authToken: String = new Buffer(`${username}:${password}`).toString('base64'); this.httpProviderRef.Ajax(LoginResponse, { method: 'POST', url: ODataHelper.joinPaths(this.repositoryUrl, 'sn-token/login'), headers: { 'X-Authentication-Type': 'Token', 'Authorization': `Basic ${authToken}` } }) .subscribe(r => { let result = this.handleAuthenticationResponse(r); sub.next(result); }, err => { this.stateSubject.next(LoginState.Unauthenticated); sub.next(false); }); return sub.asObservable(); } /** * Logs out the current user, sets the tokes to 'empty' * ``` * service.Logout(); * ``` */ public Logout(): Observable<boolean> { this.TokenStore.AccessToken = Token.CreateEmpty(); this.TokenStore.RefreshToken = Token.CreateEmpty(); this.stateSubject.next(LoginState.Unauthenticated); return new BehaviorSubject(false).asObservable(); } } |