django会话变量是否安全?

时间:2017-08-02 23:59:05

标签: python django session oauth-2.0

我正在创建一个在我们的组织中使用的应用程序,该应用程序将使用OAuth2.0根据其Office 365凭据登录用户。我正在获取一个访问令牌,我将存储在会话变量中。以下是我正在做的一个例子:

@never_cache
def authorization(request):
    microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri)
    token = ""
    try:
        users = 'https://graph.microsoft.com/v1.0/me' ##msgraph query url- 
        ##This query is purelyjust used to 
        ##authenticate user!
        token = microsoft.fetch_token(token_url,client_secret=client_secret,code=request.GET.get('code', '')) ##Code is the authorization code present
        ##in request URL
        header = {'Authorization': 'Bearer ' + token['access_token']}
        response = requests.get(url = users, headers = header)

        if int(response.status_code) != 200: ##if status code is not 200, then authentication failed. Redirect to login.
            print ('Not validated. Return to login.')
            request.session.flush()
            return redirect('http://localhost:8000/login')
    except Exception as e:
        print ('User not does not have authentication rights')
        request.session.flush()
        return redirect('http://localhost:8000/login')

    request.session['oauth_state'] = 'authorized'
    response = HttpResponseRedirect('http://localhost:8000/search')
    return response

然后我用它来检查是否' oauth_state'已设置为“已授权”。但是,我可能会更改此设置,以便使用令牌查询每个函数中的MS Graph API,以检查用户是否具有适当的权限。这是我正在做的一个例子:

def search(request):
        try:
            if (str(request.session['oauth_state']) != 'authorized'):
                print ('Not authorized')
                request.session.flush()
                return redirect('http://localhost:8000/login')
        except Exception as e:
            print ('Not authorized')
            request.session.flush()
            return redirect('http://localhost:8000/login')
    <rest of code>

这有多不安全?我是否应该将令牌传递给响应头?或者我应该摆脱这种方法,并使用django的标准身份验证和登录系统?我非常感谢OAuth2.0带来的好处,但如果这种方法危及我们的安全性,我可能会废弃它。

0 个答案:

没有答案