Guest User

Untitled

a guest
Jul 4th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.57 KB | None | 0 0
  1. "@angular/cli": "^6.0.8",
  2. "rxjs": "6.2.1",
  3.  
  4. interface TokenResponse {
  5. token: string,
  6. expiration: number
  7. }
  8.  
  9. import { EventEmitter, Inject, Injectable, PLATFORM_ID } from "@angular/core";
  10. import { isPlatformBrowser } from '@angular/common';
  11. import { HttpClient, HttpHeaders } from "@angular/common/http";
  12. import { Observable } from "rxjs";
  13. import { map, catchError } from 'rxjs/operators';
  14. import 'rxjs/Rx';
  15.  
  16. @Injectable()
  17. export class AuthService {
  18. authKey: string = "auth";
  19. clientId: string = "NetCoreAngularWeb";
  20.  
  21. constructor(private http: HttpClient,
  22. @Inject(PLATFORM_ID) private platformId: any) {
  23. }
  24.  
  25. // performs the login
  26. login(username: string, password: string): Observable<boolean> {
  27. var url = "api/token/auth";
  28. var data = {
  29. username: username,
  30. password: password,
  31. client_id: this.clientId,
  32. // required when signing up with username/password
  33. grant_type: "password",
  34. // space-separated list of scopes for which the token is
  35. // issued
  36. scope: "offline_access profile email"
  37. };
  38.  
  39. return this.http.post<TokenResponse>(url, data)
  40. .pipe(
  41. map(res => {
  42. let token = res && res.token;
  43. // if the token is there, login has been successful
  44. if (token) {
  45. // store username and jwt token
  46. this.setAuth(res);
  47. // successful login
  48. return true;
  49. }
  50.  
  51. // failed login
  52. return Observable.throw('Unauthorized');
  53. }),
  54. catchError(error => {
  55. return new Observable<any>(error);
  56. })
  57. );
  58. }
  59.  
  60. // performs the logout
  61. logout(): boolean {
  62. this.setAuth(null);
  63. return true;
  64. }
  65.  
  66. // Persist auth into localStorage or removes it if a NULL argument is given
  67. setAuth(auth: TokenResponse | null): boolean {
  68. if (isPlatformBrowser(this.platformId)) {
  69. if (auth) {
  70. localStorage.setItem(
  71. this.authKey,
  72. JSON.stringify(auth));
  73. }
  74. else {
  75. localStorage.removeItem(this.authKey);
  76. }
  77. }
  78. return true;
  79. }
  80.  
  81. // Retrieves the auth JSON object (or NULL if none)
  82. getAuth(): TokenResponse | null {
  83. if (isPlatformBrowser(this.platformId)) {
  84. var i = localStorage.getItem(this.authKey);
  85. if (i) {
  86. return JSON.parse(i);
  87. }
  88. }
  89. return null;
  90. }
  91.  
  92. // Returns TRUE if the user is logged in, FALSE otherwise.
  93. isLoggedIn(): boolean {
  94. if (isPlatformBrowser(this.platformId)) {
  95. return localStorage.getItem(this.authKey) != null;
  96. }
  97. return false;
  98. }
  99. }
  100.  
  101. [HttpPost("Auth")]
  102. public async Task<IActionResult> Auth([FromBody]TokenRequestViewModel model)
  103. {
  104. // return a generic HTTP Status 500 (server Error)
  105. // if the client payload is invalid.
  106. if (model == null) return new StatusCodeResult(500);
  107.  
  108. switch (model.grant_type)
  109. {
  110. case "password":
  111. return await GetToken(model);
  112. default:
  113. // not supported - return a HTTP 401 (Unauthorized)
  114. return new UnauthorizedResult();
  115. }
  116. }
  117.  
  118. private async Task<IActionResult> GetToken(TokenRequestViewModel model)
  119. {
  120. try
  121. {
  122. // check if there's an user with the given username
  123. var user = await UserManager.FindByNameAsync(model.username);
  124. // fallback to support e-mail address instead of username
  125. if (user == null && model.username.Contains("@"))
  126. user = await UserManager.FindByEmailAsync(model.username);
  127. if (user == null || !await UserManager.CheckPasswordAsync(user, model.password))
  128. {
  129. // user does not exists or password mismatch
  130. return new UnauthorizedResult();
  131. }
  132.  
  133. // username & password matches: create and return the Jwt token
  134. DateTime now = DateTime.UtcNow;
  135.  
  136. // add the registered claims for JWT (RFC7519)
  137. // For more info, see...
  138. var claims = new[]
  139. {
  140. new Claim(JwtRegisteredClaimNames.Sub, user.Id),
  141. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  142. new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUnixTimeSeconds().ToString())
  143.  
  144. // TODO add additional claims here
  145. };
  146.  
  147. var tokenExpirationMins = Configuration.GetValue<int>("Auth:Jwt:TokenExpirationInMinutes");
  148. var issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Auth:Jwt:Key"]));
  149.  
  150. var token = new JwtSecurityToken(
  151. issuer: Configuration["Auth:Jwt:Issuer"],
  152. audience: Configuration["Auth:Jwt:Audicnete"],
  153. claims: claims,
  154. notBefore: now,
  155. expires:
  156. now.Add(TimeSpan.FromMinutes(tokenExpirationMins)),
  157. signingCredentials: new SigningCredentials(issuerSigningKey, SecurityAlgorithms.HmacSha256)
  158. );
  159. var encodedToken = new JwtSecurityTokenHandler().WriteToken(token);
  160.  
  161. // build & return the response
  162. var response = new TokenResponseViewModel()
  163. {
  164. token = encodedToken,
  165. expiration = tokenExpirationMins
  166. };
  167. return Json(response);
  168. }
  169. catch (Exception ex)
  170. {
  171. return new UnauthorizedResult();
  172. }
  173. }
Add Comment
Please, Sign In to add comment