GithubHelp home page GithubHelp logo

cesarhernandezgt / oauth2-jwt-angular Goto Github PK

View Code? Open in Web Editor NEW

This project forked from tomitribe/oauth2-jwt-angular

0.0 2.0 0.0 827 KB

OAuth 2.0 JWT with Angular 8

License: Apache License 2.0

JavaScript 2.16% TypeScript 32.68% CSS 4.11% HTML 13.82% Java 47.23%

oauth2-jwt-angular's Introduction

Microprofile JWT Movie Chat

This web application shows how to use Microprofile JWT to secure your microservices. It uses Apache TomEE as the default Microprofile implementation.

OAuth2 + JWT (STS)

In order to work, this application requires an STS capable of generating signed JWT tokens. We use Tribestream API Gateway as it’s a complete Security Token Service. It’s also capable of doing routing and while enforcing permissions. If you want to know more, check out the website at https://tribestream.io

To start the Tribestream API Gateway on a terminal execute the following command:

mvn tag:run

The following message indicates the Tribestream API Gateway is up and running:

[INFO] Tribestream started http://localhost:8080/tag/

You can login now using on a browser the following URL: http://localhost:8080/tag/ using admin for both the username and password.

Start the movie chat application

On a new terminal execute the following command:

mvn clean install -DskipTests tomee:run

The following message indicates the application is up and running:

08-Mar-2019 11:34:07.760 INFO [main] sun.reflect.NativeMethodAccessorImpl.invoke Starting ProtocolHandler ["http-nio-8181"]
08-Mar-2019 11:34:07.765 INFO [main] sun.reflect.NativeMethodAccessorImpl.invoke Starting ProtocolHandler ["ajp-nio-8010"]
08-Mar-2019 11:34:07.767 INFO [main] sun.reflect.NativeMethodAccessorImpl.invoke Server startup in 6786 ms

You can login now using on a browser the following URL: http://localhost:8080/movies

You can test any of the following accounts: - Account alex with password password with create, update and delete role. - Account john with password password with just comments add role.

For deeper exaplanation of Microprofile JWT using this application access: https://tribestream.io/guide/en/api-gateway/microservice-security-microprofile-jwt/current/

Angular Http Interceptors

Simple Example

For your project to sign a request you might need only one interceptor or header inject.

@Injectable()
export class AuthHeaderInterceptor implements HttpInterceptor {
  constructor(private $auth: AuthService) { }
  intercept(req: RetryHttpRequest, next: HttpHandler): Observable<any> {
    return next.handle(req.clone({
      headers:
        req.headers.set(this.$auth.authHeader,
          `${this.$auth.authPrefix} ${this.$auth.authToken}`)
    }));
  }
}

Usage

For this example we added three interceptors that are injected into angular 8 project into root module providers.

import { HeaderInterceptors } from './services/header.interceptor';

...

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ...
    HeaderInterceptors
  ],
  bootstrap: [...]
})
export class AppModule { }

Our interceptors usage

Check our interceptors source and their usage:

First interceptor NoAuthHeaderInterceptor adds $$noAuth property to a request for any request that should not be signed/authorised.

@Injectable()
export class NoAuthHeaderInterceptor implements HttpInterceptor {
  constructor(private $auth: AuthService) { }
  intercept(req: RetryHttpRequest, next: HttpHandler): Observable<any> {
    if (...) {
      req.$$noAuth = true;
      return next.handle(req);
    }

    return next.handle(req);
  }
}

Second interceptor OauthHeaderInterceptor adds Authorization header to a request.

@Injectable()
export class OauthHeaderInterceptor implements HttpInterceptor {
  constructor(private $auth: AuthService) { }
  signRequest(req) {
    return req.clone({
      headers:
        req.headers.set(this.$auth.authHeader,
          `${this.$auth.authPrefix} ${this.$auth.authToken}`)
    });
  }
  intercept(req: RetryHttpRequest, next: HttpHandler): Observable<any> {
    if (req.$$noAuth) {
      return next.handle(req);
    }

    return next.handle(this.signRequest(req));
  }
}

Third interceptor RetryHeaderInterceptor checks for 401 errors and handles refresh/retry of request.

@Injectable()
export class RetryHeaderInterceptor implements HttpInterceptor {
  constructor(private $auth: AuthService) { }
  intercept(req: RetryHttpRequest, next: HttpHandler): Observable<any> {
    if (req.$$retry) {
      req.$$retry = false;
      return next.handle(req);
    }

    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        ...
        if (error.status === 401) {
          return this.$auth.refresh()
            .pipe(
              filter(auth => !!auth),
              switchMap((auth) => {
                const headers = req.headers
                  .set(this.$auth.authHeader,
                    `${this.$auth.authPrefix} ${this.$auth.authToken}`);
                const clone = req.clone({ headers }) as RetryHttpRequest;
                clone.$$retry = true;
                clone.$$noAuth = true;
                return next.handle(clone);
              })
            );
        } else {
          ...
        }
      })
    );
  }
}

oauth2-jwt-angular's People

Contributors

dexmaster avatar jgallimore avatar jeanouii avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.