question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to set Authorization Header ?

See original GitHub issue

I am using ng2-signalrin ionic 2. Issue is that i don’t know how to set authorization header. I have search but didn’t find any example.

My code for connecting to server hub.

   let options: IConnectionOptions = { qs:{userId:1}, url: "http://192.168.0.211:44337"};
                
		console.log("Stage 1");
			//Header for 'this.singalR.connect'
        this.signalR.connect(options)
            .then((connection) => {                      
        
                console.log("Client Id: " + connection.id);                     
             }, (err) => {
                console.log("SignalR Error: " + JSON.stringify(err));
            });

How to set below header ?

  var headers = new Headers({
            'Content-Type': "application/json",
            "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
        });

Note: Before implementing Authorization same code working fine as i don’t need to set authorization header.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
Usman235commented, May 31, 2017

@HNeukermans Thanks for response.

Issue it that is have two signalr client , one is in simple angularjs and other is ionic 2 .

In Simple Angularjs i’m doing following to set the header. (Which is working).

$.signalR.ajaxDefaults.headers = new Headers({
            'Content-Type': "application/json",
            "Authorization": 'Bearer ' + accessToken  //accessToken contain bearer value.
        });

I’m wondering if there is way to send headers just like above . If i go for query string option that is what you suggested then i have to change a lot of code on server side as well as on simple angularjs signalr client .

Is there any other way ?

2reactions
Jrubzjeknfcommented, Nov 30, 2017

We created a custom service where the SignalR and OAuthService are injected. Below is a basic example where the ISignalRConnection is provided through an Observable. This way, if the connection is interrupted and re-establised, you are able to automatically resubscribe to the new connection.

import { Injectable, OnInit } from '@angular/core';
import { SignalR, ISignalRConnection } from 'ng2-signalr';
import { Notice } from "app/feed/notice/notice.model";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { OAuthService } from "angular-oauth2-oidc/dist";

@Injectable()
export class SignalrService {
  private subject: Subject<ISignalRConnection>;
  public connection: Observable<ISignalRConnection>;

  constructor(private signalR: SignalR, private oauthService: OAuthService) {
    this.subject = new Subject<ISignalRConnection>();
    this.connection = this.subject.asObservable().shareReplay(1);

    if (navigator.onLine) {
      this.connect();
    }
  }

  private connect() {
    // Set auth headers.
    let $ = (<any>window).$;
    $.signalR.ajaxDefaults.headers = {
      'Content-Type': "application/json",
      "Authorization": 'Bearer ' + this.oauthService.getAccessToken()
    };

    let promise = this.signalR.connect();

    promise
      .then(x => {
        this.subject.next(x);

        x.errors.subscribe(y => {
          if (y.message.includes(`Couldn't reconnect within the configured timeout`)) {
            this.reconnect();
          }
        })
      })
      .catch(x => this.reconnect());
  }

  private reconnect() {
    let ms = 3000;
    console.log(`Manual reconnect after ${ms}ms`);
    setTimeout(() => this.connect(), ms)
  }
}

And to listen for a message, inject this SignalrService and subscribe to the connection Observable:

    this.signalrService
        .connection
        .subscribe(connection => connection
            .listenFor('your-message')
            .subscribe((yourMessage: IYourMessage) => {
                // do something
            }));
Read more comments on GitHub >

github_iconTop Results From Across the Web

Authorization - HTTP - MDN Web Docs - Mozilla
The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a ......
Read more >
http post - how to send Authorization header?
Unfornately there is no Authorization header. How should I add it correctly? Whole request sent by my code looks as follow: OPTIONS /oauth/token?grant_type= ......
Read more >
Generate an Authorization Header
Generate an Authorization Header · In the command line, type the following command, including the single quotation marks: echo -n '<user_name>:< ...
Read more >
Authorizing requests | Postman Learning Center
In the Authorization tab for a request, select OAuth 2.0 from the Type dropdown list. Specify if you want pass the auth details...
Read more >
HTTP headers: Authorization header | Web Services Tutorial
Click the below link to download the Java Source code and PPT: ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found