Skip to main content
 首页 » 编程设计

python之使用 Oauth2 在 Flask 中使用特定托管域 (hd) 对用户进行身份验证

2025年04月02日16soundcode

您好,这是我当前在我的网络应用程序中用于身份验证的 python 代码。

auth_flow = OAuth2WebServerFlow(client_id=AUTH_CLIENT_ID, 
                                client_secret=AUTH_CLIENT_SECRET, 
                                scope=AUTH_PLUS_SCOPE, 
                                redirect_uri=AUTH_CALLBACK_URI) 
 
AUTH_ARGS = { 
    'error': fields.Str(), 
    'code': fields.Str() 
} 
 
 
@auth_api.route('/', methods=['GET']) 
def get_auth_uri(): 
    if current_user and current_user.is_authenticated: 
        return redirect(LOGIN_PATH) 
    else: 
        auth_uri = auth_flow.step1_get_authorize_url() 
        return redirect(auth_uri) 
 
 
@auth_api.route('/oauth2callback', methods=['GET']) 
@use_kwargs(AUTH_ARGS) 
def oauth2_callback(error, code): 
    if error: 
        return redirect(url_for('login'), code=HTTPStatus.TEMPORARY_REDIRECT) 
    else: 
        try: 
            authenticate(code) 
            return redirect(LOGIN_PATH) 
        except Unauthorized: 
            raise APIError(HTTPStatus.UNAUTHORIZED, AUTH_FAILED_MESSAGE) 
 
 
@auth_api.route('/me', methods=['GET']) 
@login_required 
def get_current_user(): 
    return jsonify(current_user.serialized) 
 
 
@auth_api.route('/logout') 
@login_required 
def logout(): 
    logout_user() 
    return redirect(url_for('login')) 
 
 
 
def authenticate(code): 
    try: 
        credentials = _get_credentials(code) 
        user = User.get_or_create(credentials) 
        login_user(user) 
    except FlowExchangeError: 
        raise Unauthorized() 
 
 
def _get_credentials(code): 
    return auth_flow.step2_exchange(code) 

但是,现在,我的应用程序正在接受来自任何谷歌帐户地址的登录。我想限制对具有指定域(如 abc@harvard.edu)的用户登录的访问权限。我已经看到一些关于 hd 参数的答案,但我不知道如何使用它。

请您参考如下方法:

可以通过将 hd 参数附加到 auth_uri 来设置 hd 参数,如下所示

auth_uri = GOOGLE_AUTH_URI 
auth_uri = auth_uri + '?hd=' + 'example.com' 
 
auth_flow = OAuth2WebServerFlow(client_id=AUTH_CLIENT_ID, 
                            client_secret=AUTH_CLIENT_SECRET, 
                            scope=AUTH_PLUS_SCOPE, 
                            redirect_uri=AUTH_CALLBACK_URI, 
                            auth_uri=auth_uri, 
                            ) 

但是根据我的经验,hd 参数不会限制具有不同电子邮件地址的用户登录。您应该始终验证凭据。

def authenticate(code): 
    try: 
        credentials = _get_credentials(code) 
        if not credentials.id_token['email'].endswith('@example.com') 
            # abort(401) 
            raise Unauthorized() 
        user = User.get_or_create(credentials) 
        login_user(user) 
     except FlowExchangeError: 
        raise Unauthorized()