第三方登录验证

JWT方式(Google,Apple)
获取公钥
https://appleid.apple.com/auth/keys
https://www.googleapis.com/oauth2/v3/certs
公钥校验

  public static Boolean verifyAppleLoginToken(String token,String subject) throws IOException {
        //先从token中解析出HEADER部分的kid,然后从苹果提供的公钥获取url中获取生成rsa公钥所需的n和e
        DecodedJWT decodedJWT = JWT.decode(token);
        System.out.println(JSON.toJSONString(decodedJWT));
        List<Item> keyList = APPLE_KEYS.toJavaList(Item.class);
        String n = null, e = null;
        for (Item item : keyList) {
            if (item.getKid().equals(kid)) {
                n = item.getN();
                e = item.getE();
            }
        }
        //各个版本的base64解码实现不太一样,目前发现只有apache的base64可以解析成功
        BigInteger bigIntModulus = new BigInteger(1, org.apache.commons.codec.binary.Base64.decodeBase64(n));
        BigInteger bigIntPrivateExponent = new BigInteger(1, org.apache.commons.codec.binary.Base64.decodeBase64(e));
        try {
            //使用生成的RSA公钥验证token的SIGNATURE部分是否合法,(同时验证ISSUER,SUBJECT,AUDIENCE是否合法)
            RSAPublicKeyImpl rsaPublicKey = new RSAPublicKeyImpl(bigIntModulus, bigIntPrivateExponent);
            Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, null);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withSubject(subject)
                    .withAudience(AUDIENCE)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println(JSON.toJSONString(jwt));
        } catch (JWTVerificationException ex1) {
            System.out.println(ex1.getMessage());
            return false;
        } catch (InvalidKeyException ex2) {
            System.out.println(ex2.getMessage());
            return false;
        }
        return true;
    }

接口请求(Facebook)
https://graph.facebook.com/debug_token?access_token=&input_token=

OAUTH形式接口请求(Twitter)
https://api.twitter.com/1.1/account/verify_credentials.json

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Google第三方登录验证,可以按照以下步骤: 1. 创建Google API项目并获取客户端ID和客户端密钥。 - 在 Google Cloud Console 中创建项目。 - 在“凭据”页面上创建OAuth 2.0客户端ID。 - 下载凭据并将其保存到项目中。 2. 安装必要的Python包: ``` pip install google-auth google-auth-oauthlib google-auth-httplib2 ``` 3. 在Django项目中,创建一个文件 `google_auth.py` 并添加以下代码: ``` from google.oauth2 import id_token from google.auth.transport import requests def validate_google_token(token): try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), 'CLIENT_ID') # ID token is valid. Return the user's Google Account details. return idinfo except ValueError: # Invalid token return None ``` 注意:在上述代码中,需要将字符串 `CLIENT_ID` 替换为你的Google客户端ID。 4. 创建视图函数,用于处理Google登录请求: ``` from django.shortcuts import redirect from django.urls import reverse def google_login(request): # Create a state token to prevent request forgery. # Store it in the session for later validation. state = uuid.uuid4().hex request.session['state'] = state # Set the client ID, token state, and application name in the HTML while # serving it. google_auth_url = 'https://accounts.google.com/o/oauth2/auth?' \ 'response_type=code&client_id={}&redirect_uri={}&' \ 'scope=openid%20email%20profile&state={}'.format( 'CLIENT_ID', request.build_absolute_uri(reverse('google_authenticate')), state) return redirect(google_auth_url) ``` 注意:在上述代码中,需要将字符串 `CLIENT_ID` 替换为你的Google客户端ID。 5. 创建另一个视图函数,用于验证Google登录并返回用户信息: ``` def google_authenticate(request): # Verify the state token if request.GET.get('state') != request.session.get('state'): return HttpResponseBadRequest('Invalid session state.') # Exchange authorization code for access token params = { 'code': request.GET.get('code'), 'client_id': 'CLIENT_ID', 'client_secret': 'CLIENT_SECRET', 'redirect_uri': request.build_absolute_uri(reverse('google_authenticate')), 'grant_type': 'authorization_code' } response = requests.post('https://oauth2.googleapis.com/token', data=params) token_data = response.json() # Validate and decode ID token id_token = token_data.get('id_token') idinfo = validate_google_token(id_token) # Return user info return JsonResponse({ 'email': idinfo.get('email'), 'first_name': idinfo.get('given_name'), 'last_name': idinfo.get('family_name'), 'picture_url': idinfo.get('picture') }) ``` 注意:在上述代码中,需要将字符串 `CLIENT_ID` 和 `CLIENT_SECRET` 替换为你的Google客户端ID和客户端密钥。 6. 在 `urls.py` 中添加以下路由: ``` from django.urls import path from .views import google_login, google_authenticate urlpatterns = [ path('google/login/', google_login, name='google_login'), path('google/authenticate/', google_authenticate, name='google_authenticate'), ] ``` 7. 在模板中添加登录按钮,点击该按钮将跳转到Google登录页面: ``` <a href="{% url 'google_login' %}">Log in with Google</a> ``` 以上就是实现Django中Google第三方登录验证的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值