質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Angular

Angularは、JavaScriptフレームワークです。AngularJSの後継であり、TypeScriptベースで実装されています。機能ごとに実装を分けやすく、コードの見通しが良いコンポーネント指向です。

OAuth

OAuth(Open Authorization)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

5208閲覧

angularでgithubのOAuthを行う際に、CORSでブロックされる

Kunoki

総合スコア11

Angular

Angularは、JavaScriptフレームワークです。AngularJSの後継であり、TypeScriptベースで実装されています。機能ごとに実装を分けやすく、コードの見通しが良いコンポーネント指向です。

OAuth

OAuth(Open Authorization)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2018/10/11 05:31

編集2018/10/11 07:01

現在AngularでOAuthを行うアプリケーションを開発しています。
OAuthについては以下のサイトを参照しています。
https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/

内容としては、
「GETメソッドで、必要なパラメータ(client_id,scope, redirect_url, state,allow_singup)をつけて、https://github.com/login/oauth/authorize にアクセスする」
ということだと思っています。
その際、OAuth認証を行う際に投げるapiでエラーが出てしまいます。

Angular

1 2OAuthURL1: string = "https://github.com/login/oauth/authorize"; 3 4//api呼び出しメソッド内 5var httpObj = this.http.get(this.OAuthURL1, this.githubApiParam1); 6httpObj.subscribe(this.OAuth1Next, this.RequestError);
//webブラウザのコンソールより Failed to load https://github.com/login/oauth/authorize: Redirect from 'https://github.com/login/oauth/authorize' to 'https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

調べた結果、CORSという約束事でブロックされていることが分かり、Access-Control-Allow-Originの設定をする必要があることが分かりました。

その後対策を調べてみたのですが、サーバー側の.htaccessを編集するもの、リクエストヘッダーにAccess-Control-Allow-Originを追加するものなどがありました。

しかし、angularの.getメソッドには .get(URL, パラメータ)しか引数をとれず困っています。

なにか良い方法はないでしょうか。

追記
プログラムを↓のように直した結果

angular

1OAuth1() { 2 var httpObj = this.http.get(this.OAuthURL1, 3 { 4 headers: new HttpHeaders({ 5 'Content-Type': 'application/json' 6 }), 7 params: new HttpParams({ 8 client_id: this.clientId, 9 redirect_url: this.redirectUrl, 10 scope: "", // default is empty 11 state: this.state, 12 allow_singup: false // default is true 13 }) 14 }); 15 console.log(this.githubApiParam1); 16 httpObj.subscribe(this.OAuth1Next, this.RequestError); 17 }

エラー文が次のようになっています

//webブラウザより Refused to set unsafe header "Origin" Failed to load resource: the server responded with a status of 404 (Not Found) Failed to load https://github.com/login/oauth/authorize: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

Access-Control-Allow-Origin はレスポンスヘッダです。
Github APIサーバーから返却されたレスポンスを確認してください。

あと、参考までに公式リファレンスへのリンクも貼っておきます。
https://angular.jp/api/common/http/HttpClient#get
get にも色々なオプションが設定できるのがわかりますか?

投稿2018/10/11 05:48

編集2018/10/11 05:51
mather

総合スコア6753

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Kunoki

2018/10/11 05:58

エラーの際のレスポンスの確認の仕方がわからないです。現在のプログラムでは、 OAuth1() { var httpObj = this.http.get(this.OAuthURL1, this.githubApiParam1); console.log(this.githubApiParam1); httpObj.subscribe(this.OAuth1Next, this.RequestError); } private RequestError(error) { console.log("Error"); console.log(error); } となっていて、ブラウザでは HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} と表示されています。HttpErrorResponseはサーバーから返されたレスポンスとは別物ですよね? 紹介していただいた参考ページをさっき初めて見ました。参考ページをもうちょっと探してみます。ありがとうございます
mather

2018/10/11 06:24

AngularということはブラウザでJavaScriptが動作してXHRを実行しているはずなので、ブラウザの開発者ツールを確認すればどのようなリクエストが実行されているか分かるはずです。 お使いのブラウザの開発者ツールの使い方に関してはググってみてください。
Kunoki

2018/10/11 06:32

教えていただいた参考ページを見ながら、プログラムコードを変えたところ、エラーメッセージが変化しました。(正直CORSなどについてよくわかっていないので、設定すべきパラメータがたぶん間違っています) プログラム OAuth1() { var httpObj = this.http.get(this.OAuthURL1, { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Origin': "http://localhost:4200" }), params: new HttpParams({ client_id: this.clientId, redirect_url: this.redirectUrl, scope: "", // default is empty state: this.state, allow_singup: false // default is true }) }); console.log(this.githubApiParam1); httpObj.subscribe(this.OAuth1Next, this.RequestError); } エラー Refused to set unsafe header "Origin" Failed to load resource: the server responded with a status of 404 (Not Found) Failed to load https://github.com/login/oauth/authorize: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access ツールを探してみようと思います。ありがとうございます
mather

2018/10/11 06:57

> Refused to set unsafe header "Origin" Originを勝手に書き換えようとするとエラーになります。なぜなら悪意のあるサイトが信用のあるサイトからのリクエストだと偽装できてしまうからです。通常はOriginはセットしません。ブラウザが自動的にセットします。 Chromeの開発者ツールはこちらを参考にしてください。 https://www.buildinsider.net/web/chromedevtools/01
Kunoki

2018/10/11 07:03

なるほど、Originはそういうものなのですね。 参照して試してみます。なにからなにまで、ありがとうございます
Kunoki

2018/10/11 07:12

DevTools の Networkタブで確認したところ、 Headerタブ General ---------------------------------------- Request URL: https://github.com/login/oauth/authorize Request Method: OPTIONS Status Code: 404 Not Found Remote Address: 192.30.255.112:443 Referrer Policy: no-referrer-when-downgrade Response Headers---------------------------------------- Content-Type: text/html; charset=utf-8 Request Headers---------------------------------------- Provisional headers are shown Access-Control-Request-Headers: content-type Access-Control-Request-Method: GET Origin: http://localhost:4200 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 Responseタブ This request has no resposne data available となっていました
mather

2018/10/11 07:15

404 Not Found となってますが…。
Kunoki

2018/10/11 07:23

Networkタブでは404と出ていますが、コンソールのほうでは Failed to load https://github.com/login/oauth/authorize: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. と出ていたため、このエラー内容について調べています
Kunoki

2018/10/11 07:30

もしかしたら、github API の「1時間に60回しかAPIを実行できない」というルールに引っかかったのかもしれませんので、もう少し時間をおいてみます。(エディターが自動セーブすると、Angularのサーバーが自動で更新してた..)
Kunoki

2018/10/11 10:04

GET https://github.com/login/oauth/authorize と書いてあったので、apiでそのページにアクセスすればいいのかと思っていました。ありがとうございます。流れをもう一度洗いなおしてみます。 ちなみにですが、404 Not Found の件ですが、パラメータがうまく設定できていないみたいでした。 OAuth1() { var httpObj = this.http.get("https://github.com/login/oauth/authorize", new HttpParams({ 'client_id': this.clientId, 'redirect_url': this.redirectUrl, 'scope': "", // default is empty 'state': this.state, 'allow_singup': true // default is true }) ); console.log(this.githubApiParam1); httpObj.subscribe(this.OAuth1Next, this.RequestError); } となおしたら、404 Not Fount が 302 Found に変化しました。エラー内容も最初の状態み戻りました
Kunoki

2018/10/11 10:31

<a href="https://github.com/login/oauth/authorize? client_id=「client_idの文字列」& redirect_url=「redirectUrlの文字列」& scope= & state=「apiService.stateの文字列」& allow_singup=ture">認証</a> htmlで普通にリンクを作ったらいけました!(あの努力はいったい) htmlのリンクにGET機能があることをしりませんでした。 ながながとお付き合いしていただいて、ありがとうございました
mather

2018/10/11 10:33

お疲れ様でした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問