CESCO
CESCO

Reputation: 7758

How to access request header with Angular2?

ON my golang backend after a success oauth2 request for facebook I redirect whe user to my app's dashboard like so:

w.Header().Set("Authorization", fmt.Sprintf("Bearer %s", tokenString))
http.Redirect(w, r, "http://" + r.Host + "/dashboard?jwt=" + tokenString, http.StatusFound)

Then on the dashboard initialization I do somenthing like:

params:RouteParams;


constructor(private _router:Router, private _jwt:JWTService, private _params:RouteParams, private location:Location) {
    this.params = _params;


}


consol() {
    var redirect_url = encodeURIComponent("http://localhost:9000/api/facebook/");
    var url = "https://www.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri="+ redirect_url + "&response_type=code&scope=email+user_location+user_about_me"
    window.location.href=url;
}

ngOnInit() {
    this.token = '';
    console.log(this.params);
    if (this.params.params['jwt'] != null) {
        console.log(this.params);
        localStorage.setItem('jwt', this.params.params['jwt']);
        this.location.replaceState('/dashboard')
    }
    this.Bouncer();
}

I want to avoid making my url dirty, not even for a few seconds. I wish I could inspect the request headers, because I am sending the jwt through that as well.

Updated

The original request is done through a angular2-material button

 <div md-raised-button color="warn" (click)="consol()">Login to FACEBOOK</div>

Upvotes: 1

Views: 794

Answers (1)

CESCO
CESCO

Reputation: 7758

First I create a pop up window/tab.

    var url = "https://accounts.google.com/o/oauth2/auth?client_id="
                    + clientid + "&redirect_uri="
                    + redirect_url + "&response_type=code&scope="
                    + scope;
    window.open(url);

This goes to google and hit my server on the way back,at the redirect url. Which serves the script tag below inside this popup. It actually just run a command on the windows that created this popup , in this case my SPA, with my application token as a parameter and then closes it.

w.Write([]byte(`
                    <script>
                        var token="` + token + `";
                        function CloseMySelf() {
                            try {
                                window.opener.angularComponentRef.runThisFunctionFromOutside(token);
                            }
                            catch (err) {}
                            window.close();
                            return false;
                        }
                        CloseMySelf();
                    </script>

    `))

This is the function that it call. This method needs to be made public like this question shows.

runThisFunctionFromOutside(token) {
    localStorage.setItem('jwt', token);
    location.href = "../dashboard";
}

Upvotes: 1

Related Questions