Breeze / breeze-client

Breeze for JavaScript clients
MIT License
38 stars 16 forks source link

API Bearer authentication support #48

Closed lvasiliou closed 3 years ago

lvasiliou commented 3 years ago

Hi i am trying to secure my API using bearer header/token. Is there a simple way to achieve this or is it a matter of writing an adapter from scratch?

softronsts commented 3 years ago

At client, you need to wire up the authentication/signin in auth service and for every http request you can attach the token via HttpInterceptor. Sample implementation as follows

import { Injectable } from "@angular/core";
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from "@angular/common/http";
import { Observable } from "rxjs";
import { StorageService } from "../@services/storage.service";
import { tap, finalize } from "rxjs/operators";
import { NgxSpinnerService } from "ngx-spinner";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  count = 0;
  constructor(private storage: StorageService, private spinner: NgxSpinnerService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.spinner.show();

    const token = this.storage.get("auth.access_token");
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`,
      },
    });

<snipped>
lvasiliou commented 3 years ago

Thanks for the reply but regrettably I am using React.

steveschmitt commented 3 years ago

@lvasiliou There's probably a "React way" of doing this, but here's an example of the Breeze way.

// example of adding headers to requests via requestInterceptor
AjaxFetchAdapter.register().requestInterceptor = (req => {
    console.log(req);
    req.config.headers.Authorization = "Bearer oiwjeglkwjelkj";
  }) as any;

EDIT: this is a simpler way:

// example of adding headers to requests via defaultSettings
AjaxFetchAdapter.register().defaultSettings = { headers: { "Authorization": "Bearer oiwjeglkwjelkj"}};

I've added this example code to entity-manager-provider.ts in the northwind-demo sample application.

You would still need to implement the creation and handling of the actual tokens, perhaps using local storage as @softronsts suggests above.

BTW, when I looked into this I realized that the declared type for requestInterceptor is all wrong in Breeze. I'll fix it for the next release.

P.S. Why "regrettably"? :)

lvasiliou commented 3 years ago

Angular always felt more mature and scalable, with features out of the box. Also way better documented. React works but the focus is too much on components rather than apps.

steveschmitt commented 3 years ago

@lvasiliou Shall I close this issue?

lvasiliou commented 3 years ago

@lvasiliou Shall I close this issue?

Yes I was able to inject the bearer token