如何设置Django默认使用Instagram进行身份验证? 试过django-socialauth,但没有结果。 哪种方式最好?
答案 0 :(得分:0)
首先将用户重定向到此网址很简单
BASE_URL = "https://api.instagram.com/oauth/authorize/?"
REDIRECT_URI = "http://127.0.0.1:5000/grant-access"
url = BASE_URL + "client_id={}&redirect_uri={}&response_type=code".format(CLIENT_ID, REDIRECT_URI)
return HttpResponseRedirect(url)
然后
REQUEST_ACCESS = "https://api.instagram.com/oauth/access_token/?"
def grant_access(request):
code = request.GET.get('code')
payload = {'client_id': CLIENT_ID, 'client_secret':CLIENT_SECRET, 'grant_type':'authorization_code','redirect_uri': REDIRECT_URI, 'code': code}
resp = requests.post(REQUEST_ACCESS, data= payload)
response = json.loads(resp.text)
现在,您将把访问令牌保存到db中以供以后使用并登录
答案 1 :(得分:0)
检查出来:
我在python-instagram中找到了来自sample_app.py的解决方案:)并与django auth同步
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from instagram import client
from app.models import UserProfile
unauthenticated_api = client.InstagramAPI(**settings.INSTAGRAM_CONFIG)
@login_required
def index(request):
return render(request, 'app/index.html', {})
def on_login(request):
try:
url = unauthenticated_api.get_authorize_url(scope=["likes","comments"])
return render(request, 'app/login.html', {'url': url})
except Exception as e:
print(e)
def on_callback(request):
code = request.GET.get("code")
if not code:
return "Missing code"
try:
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
if not access_token:
return "Could not get access token"
api = client.InstagramAPI(access_token=access_token, client_secret=settings.INSTAGRAM_CONFIG['client_secret'])
request.session['access_token'] = access_token
print "%s" % access_token
except Exception as e:
print(e)
print "%s" % user_info
print "%s" % user_info['username']
user, created = User.objects.get_or_create(username=user_info['username'])
user.backend = 'django.contrib.auth.backends.ModelBackend'
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/app/')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("No login.")
@login_required
def on_logout(request):
logout(request)
return HttpResponseRedirect('/app/')