#Basic Auth Calling Get with HttpClient

9 messages · Page 1 of 1 (latest)

mystic python
#
  login(email: string, password: string) : Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa(`${email}:${password}`)
      }),
      observe: 'response' as 'body' // Optional: Use this if you need the full response
    };
    return this.http.get(`${this.baseUrl}/api/token`,httpOptions);
  }

whenever I call this function in service it gives me browser popup to enter username and password. I'm already passing that

lyric canopy
#

Does the password or email contain non-ascii characters? btoa does not support them.

Can you check in the devtools network tab if the header is sent correctly?
Also note that Authorization header requires CORS, if the request crosses domain origins.

dull relic
#

can you show your console errors ?

mystic python
#

hi

#

sorry I was afk

#

there are no errors actually I get this prompt even though I specified email and password

mystic python
#

I think I know the problem now. I have auth interceptor which sets authorization as bearer token, how to let angular know that for 1 particular request do not intercept

#

and yes it fixed the problem but is there any better way?

export const authenticationInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next:
    HttpHandlerFn) => {
    if (req.url.includes('/api/token') || req.headers.has('Use-Basic-Auth')) {
        const basicAuthReq = req.clone();
        return next(basicAuthReq);
    } else {
        const modifiedReq = req.clone({
            headers: req.headers.set('Authorization', `Bearer ${sessionStorage.getItem('token')}`),
        });

        return next(modifiedReq);
    }
};
lyric canopy