您的位置:首页 > 编程语言 > Go语言

利用django oauth2_provider在自己的项目里实现token

2017-10-29 10:11 381 查看
先要确保在本地一个位置创建一个django应用,并确保本地安装有oauth2_provider包,并将oauth2_provider注册进django settings app;之后同步数据库就可以使用了;别忘了在进入数据库创建一个oauth2应用;具体操作,可以参考相关文档;剩下的不废话,直接粘代码:
# 引入需要使用的包
import sys
import os
import django
# 在自己的项目里将django项目引入环境变量
sys.path.append('/xxxx/xxxx/<django project/>')
os.environ['DJANGO_SETTINGS_MODULE'] = '<django project/>.settings'django.setup()
# 引入需要用到的oauth2包
from oauthlib.oauth2.rfc6749.endpoints.pre_configured import Serverfrom oauth2_provider.oauth2_validators import OAuth2Validator
# 创建token
# username: 用户名
# password:密码
# client_id: 你自己建立的应用的client_id
# client_secret: 你自己建立的应用的client_secret
def create_token(username, password, client_id, client_secret):uri = '/oauth/token/'http_method = 'POST'body = r"username=%s&password=%s&grant_type=password&client_id=%s&client_secret=%s" %(username, password, client_id, client_secret)headers = {}extra_credentials = Noneheaders, token, status_code = Server(OAuth2Validator()).create_token_response(uri, http_method, body, headers, extra_credentials)return headers, token, status_code
# 刷新token
# password:
# refresh_token: 刷新token,从获取token方法中获取
# client_id: 你自己建立的应用的client_id
# client_secret: 你自己建立的应用的client_secret
def refresh_token(refresh_token, client_id, client_secret):uri = '/oauth/token/'http_method = 'POST'body = r"refresh_token=%s&client_id=%s&client_secret=%s&grant_type=refresh_token" %(refresh_token, client_id, client_secret)headers = {}extra_credentials = Noneheaders, token, status_code = Server(OAuth2Validator()).create_token_response(uri, http_method, body, headers, extra_credentials)#print Server(OAuth2Validator()).create_token_response(uri, http_method, body, headers, extra_credentials)return headers, token, status_code

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django