Instagramの認証を読みながら実際に、ログイン方法について調べる。
Google App Engineを使った場合は、下のように実装できるようだ。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import webapp2
import json
import urllib
from google.appengine.api import urlfetch
class LoginInstagram(webapp2.RequestHandler):
def get(self):
self.redirect("https://api.instagram.com/oauth/authorize/?client_id=hoge&redirect_uri=http%3A%2F%2Ffoo.appspot.com%2Ftest%2Finsta%2Fredirect&response_type=code")
class RedirectFromInstagram(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
code = self.request.get('code')
url = "https://api.instagram.com/oauth/access_token"
payload = urllib.urlencode({
"client_id":"hoge",
"client_secret":"hoge_secret",
"grant_type":"authorization_code",
"redirect_uri":"http://foo.appspot.com/test/insta/redirect",
"code":str(code)
})
result = urlfetch.fetch(
url=url,
payload=payload,
method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
if result.status_code == 200:
#tokenの表示
self.response.out.write(result.content)
app = webapp2.WSGIApplication([
('/test/insta', LoginInstagram),
('/test/insta/redirect', RedirectFromInstagram)
],debug=False
)Oauth2だとこんなに簡単なものかとびっくりしてしまった。ライブラリなどを使わずに実装できてしまうのである。
Oauth2は、どんどん普及してほしいなと思う昨今である。
0 コメント:
コメントを投稿