如何使用Angular2访问请求头?

huangapple go评论107阅读模式
英文:

How to access request header with Angular2?

问题

在我的Golang后端中,当成功进行Facebook的OAuth2请求后,我会将用户重定向到我的应用程序的仪表板,代码如下:

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

然后,在仪表板初始化时,我会执行以下操作:

import { Router, RouteParams } from 'angular2/router';
import { JWTService } from 'path/to/JWTService';
import { Location } from 'angular2/platform/common';

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();
}

我希望避免使我的URL变得混乱,即使只有几秒钟。我希望能够检查请求头,因为我也通过请求头发送JWT。

更新

原始请求是通过Angular2 Material按钮完成的:

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

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(&quot;Authorization&quot;, fmt.Sprintf(&quot;Bearer %s&quot;, tokenString))
http.Redirect(w, r, &quot;http://&quot; + r.Host + &quot;/dashboard?jwt=&quot; + 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(&quot;http://localhost:9000/api/facebook/&quot;);
	var url = &quot;https://www.facebook.com/dialog/oauth?client_id=xxxx&amp;redirect_uri=&quot;+ redirect_url + &quot;&amp;response_type=code&amp;scope=email+user_location+user_about_me&quot;
	window.location.href=url;
}

ngOnInit() {
	this.token = &#39;&#39;;
	console.log(this.params);
	if (this.params.params[&#39;jwt&#39;] != null) {
		console.log(this.params);
		localStorage.setItem(&#39;jwt&#39;, this.params.params[&#39;jwt&#39;]);
		this.location.replaceState(&#39;/dashboard&#39;)
	}
	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

 &lt;div md-raised-button color=&quot;warn&quot; (click)=&quot;consol()&quot;&gt;Login to FACEBOOK&lt;/div&gt;

答案1

得分: 1

首先,我创建一个弹出窗口/标签。

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

这将跳转到谷歌,并在返回途中命中我的服务器,使用重定向URL。在这个弹出窗口中提供以下脚本标签。实际上,它只是在创建此弹出窗口的窗口(在这种情况下是我的SPA)上运行一个命令,并将我的应用程序令牌作为参数传递,然后关闭它。

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

这是被调用的函数。这个方法需要像这个问题所示的那样被公开。

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

First I create a pop up window/tab.

	var url = &quot;https://accounts.google.com/o/oauth2/auth?client_id=&quot;
					+ clientid + &quot;&amp;redirect_uri=&quot;
					+ redirect_url + &quot;&amp;response_type=code&amp;scope=&quot;
					+ 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(`
					&lt;script&gt;
						var token=&quot;` + token + `&quot;;
						function CloseMySelf() {
							try {
								window.opener.angularComponentRef.runThisFunctionFromOutside(token);
							}
							catch (err) {}
							window.close();
							return false;
						}
						CloseMySelf();
					&lt;/script&gt;

	`))

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

runThisFunctionFromOutside(token) {
	localStorage.setItem(&#39;jwt&#39;, token);
	location.href = &quot;../dashboard&quot;;
}

huangapple
  • 本文由 发表于 2016年4月17日 01:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/36667233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定