CMU OAuth Angular TypeScript

From CMU ITSC Network

Introduction

Authorization Code Flow
CMUOAuth-authozizationcode flow.jpg
from CMU OAuth Authorization Code Grant

Authorization Code Grant for Angular TypeScript

หลังจากทำการ Login with CMUOAuth เรียบร้อยแล้วระบบจะทำการส่ง authorization code กลับมาในรูปแบบ callback?code=[authorization_code] ดังตัวอย่าง

Angular oauth 01.png

เมื่อ login เสร็จระบบจะ redirect ไปยังหน้า client application ดังรูปข้างต้น จากนั้นทำการนำ authorization_code จากหน้า request.component.ts ส่งไปขอ Token ในหน้า token-interceptor.service.ts หลังจากนั้นให้เก็บ token ไว้ใน sessionStorage จากหน้า auth.service.ts

request.component.ts
 constructor(private http: HttpClient, private router: Router, handler: HttpBackend, private auth: AuthService, private location: Location) {
    this.http = new HttpClient(handler);
  }
ngOnInit() {
    const str = this.router.url.split('=');
    const url = (str[1]);
    this.http.get('https://yourclientapplication.com/callback?code=' + url)
      .subscribe(res => {
        this.auth.setToken(res);
        this.location.go('accounts');
        this.reload();
      });
  }
  public reload(): any {
    location.reload();
  }

auth.service.ts
@Injectable()
export class AuthService {

  constructor(private router: Router) {
  }

  getToken() {
    return sessionStorage.getItem('accessToken');
  }

  setToken(res) {
    sessionStorage.setItem('accessToken', res.access_token);
  }

token-interceptor.service.ts
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
 constructor(private authservice: AuthService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const idToken = this.authservice.getToken();

    if (idToken) {
      const cloned = req.clone({
        headers: new HttpHeaders({
          Authorization: `Bearer ${idToken}`
        })
      });
      return next.handle(cloned).pipe(catchError((err) => {
        if ([403, 401].indexOf(err.status) !== -1) {
          this.authservice.logoutUser();
          location.reload(true);
        }
        return throwError(err);
      }));
    }

เมื่อทำการขอ access token สำเร็จ ระบบจะส่งค่า token กลับคืนมาดังนี้

Angular oauth 02.png