新浪微博第三方登录使用的是OAuth2.0,开发前提已经注册开发者帐号,是开发者。

OAuth简介

OAuth: OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容。

具体开发步骤

第一步:准备阶段

打开微博开发平台,并登录你的新浪微博账号。再点击导航上的“微链接”--> “网站接入”。







创建完应用后再基本信息里就可以拿到App Key和App Secret。在开发阶段可以直接拿来使用,如果网站上线需要完善等级信息。





微博第三方登录的大体步骤:先跳转到用户登录界面,同意后回调到填写的回调页面,获得code码,通过code码获取access_token,其中包含用户的唯一表示uid。

第一步:具体开发

  • 创建web应用

    创建完成之后,打开models.py文件,编写模型:
class Users(models.Model):
uid = models.CharField(max_length=64, null=True) # 微博的关联uid
nickname = models.CharField(max_length=30, null=True) # 用户昵称
head = models.CharField(max_length=100, null=True) # 用户头像
sex = models.CharField(max_length=2, null=True) # 性别
register_time = models.DateTimeField('保存日期') # 注册时间
register_ip = models.CharField(max_length=30, null=True) # 注册ip
last_time = models.DateTimeField('最后修改日期') # 最后一次登录时间

模型用于存储微博登录返回的uid值。这个uid是与微博一一对应。

在总的urls路由中,加入对应应用路由。

from django.contrib import admin
from django.urls import include, path urlpatterns = [
path('login/', include('login.urls')), # 登录模块
]

打开对应应用目录下urls.py文件,填写对用的路由:

from django.urls import path
from . import views urlpatterns = [
path('oauth/weibo/login', views.weibo_login), # 微博授权页面
path('weibo/connect/callback.php', views.weibo_get_code), # 微博回调页面
]

oauth/weibo/login和weibo/connect/callback.php,分别是打开授权页面和回调地址。

大致步骤是授权之后,得到uid。判断这个uid是否存在数据库中。若存在,则直接登录对应的用户即可;若不存在,则获取调取获取用户信息的新浪接口,获取用户信息。

  • 开发登录模块

    1.在工程目录settings.py中设置常量
'''微博登录常量'''
WEIBO_APP_ID = "App Key"
WEIBO_APP_KEY = "App Secret"
WEIBO_REDIRECT_URI = "回调地址"

2.在对应应用的文件夹下创建wb_oauth.py文件,编辑wb_oauth.py文件:

import requests
import json class OAuthWB:
def __init__(self, client_id, client_key, redirect_uri):
self.client_id = client_id
self.client_key = client_key
self.redirect_uri = redirect_uri def get_access_token(self, code): # 获取用户token和uid
url = "https://api.weibo.com/oauth2/access_token" querystring = {
"client_id": self.client_id,
"client_secret": self.client_key,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": self.redirect_uri
} response = requests.request("POST", url, params=querystring) return json.loads(response.text) def get_user_info(self, access_token_data):
url = "https://api.weibo.com/2/users/show.json" querystring = {
"uid": access_token_data['uid'],
"access_token": access_token_data['access_token']
} response = requests.request("GET", url, params=querystring) return json.loads(response.text)

3.编辑对应应用的文件夹下views.py文件:

from .wb_oauth import OAuthWB
from django.conf import settings # 引入常量
def weibo_login(request):# 跳转授权页面
return HttpResponseRedirect(
'https://api.weibo.com/oauth2/authorize?client_id=' + settings.WEIBO_APP_ID + '&redirect_uri=' + settings.WEIBO_REDIRECT_URI) def weibo_get_code(request):
"""登录之后,会跳转到这里。需要判断code和state"""
code = request.GET.get('code', None)
sina = OAuthWB(settings.WEIBO_APP_ID,
settings.WEIBO_APP_KEY,
settings.WEIBO_REDIRECT_URI)
user_info = sina.get_access_token(code)
time.sleep(0.1) # 防止还没请求到token就进行下一步
# 通过uid查询出是否是新用户,新用户则注册登录
is_user_exist = models.Users.objects.filter(uid=user_info['uid']).first()
if is_user_exist is not None:
# 存在直接登录
pass
else:
#不存在获取用户信息
new_user_info = sina.get_user_info(user_info)
users_dict = {
"uid": new_user_info['id'],
'description': new_user_info['description'],
"head": new_user_info['profile_image_url'],
"nickname": new_user_info['name'],
}
users_table_obj = models.Users.objects.create(**users_dict).id

注:获取邮箱地址的接口是属于高级权限,需要先通过审核,然后在我的应用中的接口管理中申请。新浪提供的API测试页面

最新文章

  1. 清晰易懂TCP通信原理解析(附demo、简易TCP通信库源码、解决沾包问题等)C#版
  2. jQuery 2.0.3 源码分析 样式操作
  3. sky简介
  4. babyClock 1.0发布(Android2.2以上)
  5. 2016.6.13 php与MySQL数据库交互之数据库中的商品信息展示
  6. POJ 1419 Graph Coloring(最大独立集/补图的最大团)
  7. ssh-keygen+ssh-copy-id 在linux下实现ssh无密码登录访问(转)
  8. Server Profiler
  9. postsharp初体验
  10. 一种高斯模糊渐变动画的实现-b
  11. phpstudy 下开启openssl
  12. Log4j与common-logging
  13. 【UVA10603】Fill (构图+最短路)
  14. 配置Myeclipse中的项目部署到服务器,报the selected server is enabled, but is not configured properly.
  15. MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
  16. shell中冒号 : 用途说明
  17. mysql-笔记-类型转化
  18. Wireshark的基本使用——过滤器
  19. poj2965 【枚举】
  20. 【三分】light bulb(zoj3203)

热门文章

  1. Linux_LVM Couldn't find device with uuid
  2. mac book 华为C8815不能debug
  3. 安全测试之session,cookie
  4. python's thirty-first day for me re模块
  5. kettle init oracle jdbc
  6. mssql server修改数据库文件位置 此种方法暂未测试成功
  7. 第一次接触python:学习最简单的print及变量
  8. SerialPort缓冲区
  9. 【知识碎片】CSS 篇
  10. 通过class类获取类的方法信息