Home How to consume rest service with basic auth from angular 4
Reply: 2

How to consume rest service with basic auth from angular 4

Venkatesh K
1#
Venkatesh K Published in 2017-12-07 11:08:37Z

Hi present i am developing angular 4 application. In this we have to consume rest service with basic authorization. so please help how to consume rest service with basic auth.

thanks in advance.

federico scamuzzi
2#
federico scamuzzi Reply to 2017-12-07 11:33:01Z

.this is what i do usually for auth and store the token in my localstorage .. it consume a WebAPI Asp.net REst endpint (but it is indifferent) .. only one things..this is in Content - Type : application/x-www-form-urlencoded

so if you want to use the normal application/json ..you simply DON'T HAVE TO OVERRIDE the headers of the login calls (

let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');

)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { Auth, LoginData } from '../models/index';
import { environment } from '../../../environments/environment';
import { URLSearchParams, RequestOptions } from '@angular/http';


@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private http: HttpClient) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }


  /**
   * METHOD TO DO LOGIN TO BACK END and STORE IN LOCALSTORAGE
   * @return {Auth} Auth data
   */
  public Login(data: LoginData): Observable<Auth> {

    let headersForm = new Headers();
    headersForm.append('Content-Type', 'application/x-www-form-urlencoded');

    let dataForm = new URLSearchParams();

    dataForm.append('grant_type', 'password');
    dataForm.append('userName', data.userName);
    dataForm.append('password', data.password);
    let body = dataForm.toString();
    //  let body = 'userName=' + data.userName + '&password=' + data.password + '&grant_type=password';

    //var encoded = "grant_type=password&userName=" + data.userName + "&password=" + data.password;
    return this.http.post<Auth>(environment.API_URL + 'Token', body)

      .map((res) => {
        if (res && res.access_token) {
          localStorage.setItem('AuthData', JSON.stringify({ access_token: res.access_token, username: res.userName }));
          this.loggedIn = true;

          if (localStorage.getItem("Settings") === null) {
            let settingObj = {
              unit: 'min',
              refreshTime: 1,
              help: false,
              autoRefresh: false
            }

            localStorage.setItem('Settings', JSON.stringify(settingObj));
          }

        }

        return res as Auth;
      });
  }

  /**
   * MEthod to Log Out
   */
  public logout(): Observable<void> {
    return this.http.post(environment.API_URL + 'Account/LogOut',{data:1}).map(() => {
      localStorage.removeItem('AuthData');
      localStorage.removeItem('CurrentUser');
      localStorage.removeItem('filterDashboard');
      this.loggedIn = false;

    });

  }

  /**
   *  Method to know if is logged or not
   */
  public isLoggedIn(): boolean {
    return this.loggedIn;
  }

  /**
   *  Method to set logged
   */
  public setLoggd() {
    this.loggedIn = true;
  }


}

and Auth.ts class file:

export class Auth {
    public access_token: string;
    public userName: string;

}

Hope it helps you!

Venkatesh K
3#
Venkatesh K Reply to 2017-12-09 15:05:47Z

Presently i am using the following style

let headers = new Headers();
headers.append('Authorization', 'Basic bWFoZXNoazptYWhlc2g=');
let opts = new RequestOptions();
opts.headers = headers;

this.http.get('http://localhost:8080/job/Library%20Manager/api/json?USER=a150fadfe99325644f45a2768c2d4d40&pretty=true',opts).subscribe(data => {

  console.log("sample for testing::::"+data);
});

i am getting authentication error but getting success response when i tried from all types of rest clients like postman, onsomnia.

i tried for different rest services also. getting same type problem for all rest services i have tried.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353911 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO