login(username: string, password: string){ let headers = new Headers({ "content-type": "application/json;charset=utf-8"}); let options = new RequestOptions({ headers: headers }); return this.http.post('http://localhost:8080/login', ({ username: username, password: password }), options) .map((res : any) => { if (res.status === 200) { this.commonToken = res.json(); let data = this.commonToken; this.accessToken = JSON.stringify(data.accessToken); this.refreshToken = JSON.stringify(data.refreshToken); sessionStorage.setItem('accessToken', this.accessToken); sessionStorage.setItem('refreshToken', this.refreshToken); return true; } }) };
Here it is worth making a digression and notice that sessionStorage lives until the tab / browser is closed, and if the user closes it, all the content is discarded, and as a result, the token is lost. Alternative: localStorage or cookies . In this case, the token will remain with the user until manual deletion.There is still refreshToken. About him a little later.
However, there are some pitfalls. What kind of stones can be found in this article .
import ApolloClient, { createNetworkInterface } from 'apollo-client'; const networkInterface = createNetworkInterface({ uri: 'http://localhost:8080/graphql', opts: { mode: 'cors' } }); networkInterface.use([ { applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {}; } if (sessionStorage.getItem('accessToken')) { req.options.headers['authorization'] = `${JSON.parse(sessionStorage.getItem('accessToken'))}`; } next(); } } ]); const apolloClient = new ApolloClient({ networkInterface }); export function provideClient(): ApolloClient { return apolloClient; } export class GraphqlClient{}
private TokenAuthentication processAuthentication(TokenAuthentication authentication) throws AuthenticationException { String token = authentication.getToken(); DefaultClaims claims; try { claims = (DefaultClaims) Jwts.parser().setSigningKey(DefaultTokenService.KEY).parse(token).getBody(); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { throw new AuthenticationServiceException("Invalid JWT token:", ex); } catch (ExpiredJwtException expiredEx) { throw new AuthenticationServiceException("JWT Token expired", expiredEx); } return buildFullTokenAuthentication(authentication, claims); if (claims.get("TOKEN_EXPIRATION_DATE", Long.class) == null) throw new AuthenticationServiceException("Invalid tokens"); Date expiredDate = new Date(claims.get("TOKEN_EXPIRATION_DATE", Long.class)); if (expiredDate.after(new Date())) return buildFullTokenAuthentication(authentication, claims); else throw new AuthenticationServiceException("Token expired date error"); } private TokenAuthentication buildFullTokenAuthentication(TokenAuthentication authentication, DefaultClaims claims) { String username = claims.get("username", String.class); Long userId = Long.valueOf(claims.get("userId", String.class)); String auth = claims.get("authorities", String.class); if(Roles.REFRESH_TOKEN == auth) { throw new AuthenticationServiceException("Refresh token can't be used for authorization!!!"); } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(auth)); TokenAuthentication fullTokenAuthentication = new TokenAuthentication(authentication.getToken(), true, authorities, username, userId); return fullTokenAuthentication; }
refresh() { let token = sessionStorage.getItem('accessToken'); let refToken = sessionStorage.getItem('refreshToken'); let headers = new Headers({ "content-type": "application/x-www-form-urlencoded"}); let options = new RequestOptions({headers: headers}); let body = new URLSearchParams(); body.set('RefreshToken', refToken); if (token != null && refToken != null) { return this.http.post('http://localhost:8080/login/refresh', body, options) .subscribe((res : any) => { if (res) { this.commonToken = res.json(); let data = this.commonToken; this.accessToken = JSON.stringify(data.accessToken); sessionStorage.setItem('accessToken', this.accessToken); } }) } else { console.error('An error occurred'); } }
import { Injectable } from '@angular/core'; import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router'; import {JwtHelper} from "angular2-jwt"; import {AuthService} from "./auth.service"; @Injectable() export class AuthGuard implements CanActivate { jwtHelper: JwtHelper = new JwtHelper(); constructor(private authService: AuthService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { let accessToken = sessionStorage.getItem('accessToken'); let refreshToken = sessionStorage.getItem('refreshToken'); if (accessToken && refreshToken) { if (this.jwtHelper.isTokenExpired(accessToken)){ this.authService.refresh() } else { return true } } this.router.navigateByUrl('/unauthorized'); } }
Source: https://habr.com/ru/post/336082/
All Articles