苹果asa对接生成token代码

本文介绍如何在苹果广告平台上通过生成公钥、私钥来获取clientId、teamId及keyId,并利用Java代码实现JWT令牌的创建过程,最终获得OAuth token以完成客户端认证。

苹果广告后台获取clientId、teamId、keyId

广告账户管理员邀请用户并且授予相应权限,填写用户姓名、姓氏、AppleId并选择需要授予的权限,受邀请用户会收到一封带有安全代码的电子邮件,用户根据邮件激活码激活账户

生成对应的公钥、私钥

上传公钥,生成对应的clientId、teamId、keyId

生成客户端秘钥(JWT令牌)、并且获取token

java代码实现:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
@Override
public String getOAuthToken() {
    
    PrivateKey privateKey = jwtUtil.loadPrivateKey("私钥");
    String keyId = "";
    String teamId = "";
    String clientId = "";
    String audience = "https://appleid.apple.com";

    JwtParamsReqDto JwtParams = new JwtParamsReqDto();
    JwtParams.setId(keyId);
    JwtParams.setIssuer(teamId);
    JwtParams.setSubject(clientId);
    JwtParams.setSigningKey(privateKey);
    JwtParams.setAudience(audience);
    try {
        // 拿到secret去获取token
        String secret = jwtUtil.createJWT(JwtParams);
        return asaClientHttp.getToken(clientId, secret);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

// 以下为获取token
public String getToken(String clientId, String clientSecret)
            throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    String url = "https://appleid.apple.com/auth/oauth2/token?";
    HttpPost httpPost = new HttpPost(url);

    // 设置请求的header
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

    // 设置请求的参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("client_id", clientId));
    nvps.add(new BasicNameValuePair("client_secret", clientSecret));
    nvps.add(new BasicNameValuePair("grant_type", "client_credentials"));
    nvps.add(new BasicNameValuePair("scope", "searchadsorg"));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

    // 执行请求
    HttpResponse response = httpClient.execute(httpPost);

    // 打印执行结果
    String resp = EntityUtils.toString(response.getEntity(), "utf-8");

    LOGGER.info("http : {}  ,and response {}", url, resp);
    return resp;
}

JWT工具类

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtUtil {

    //Sample method to construct a JWT
    public String createJWT(JwtParamsReqDto jwtParams) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.ES256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //We will sign our JWT with our ApiKey secret
        // byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
        // Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        // SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

        long expMillis = nowMillis + jwtParams.getTtlMillis();
        Date exp = new Date(expMillis);
        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder()
                .setId(UUID.randomUUID().toString())//1. 这个是JWT的唯一标识,一般设置成唯一的,这个方法可以生成唯一标识
                .setIssuedAt(new Date())
                .setSubject(jwtParams.getSubject())//2. 签发人,也就是JWT是给谁的
                .setAudience(jwtParams.getAudience())
                .setIssuer(jwtParams.getIssuer())
                .signWith(signatureAlgorithm,jwtParams.getSigningKey())//3.这个地方是生成jwt使用的算法和秘钥
                .setExpiration(exp);

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }

    public PrivateKey loadPrivateKey(String privateKeyStr) {
        try {
            final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyStr));
            return KeyFactory.getInstance("EC").generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new BizException("500", e.getMessage());
        }
    }

    public PublicKey loadPublicKey(String publicKeyStr) {
        try {
            return KeyFactory.getInstance("EC")
                    .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr)));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new BizException("500", e.getMessage());
        }
    }
}

### Django 中生 Token代码实现方法 在 Django 中生 Token 可以通过多种方式实现,以下是基于引用中的内容以及常见实践所提供的解决方案。 #### 方法一:自定义 Token逻辑 可以通过编写一个工具函数来生并返回 Token。以下是一个简单的 `create_token` 函数示例: ```python import jwt from datetime import datetime, timedelta from django.conf import settings def create_token(user_id): payload = { 'user_id': user_id, 'exp': datetime.utcnow() + timedelta(days=7), # 设置过期时间为7天 'iat': datetime.utcnow(), # 发行时间 } token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') # Python3 需要解码为字符串 ``` 上述代码展示了如何使用 PyJWT 库生 JWT Token[^1]。Token 中包含了用户的 ID 和一些元数据(如发行时间和过期时间),并通过项目的密钥加密签名。 --- #### 方法二:集 djangorestframework-jwt 插件 如果项目已经集了 `djangorestframework-jwt`,可以直接利用其内置功能生 Token。下面展示了一个登录视图的实现: ```python from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_jwt.settings import api_settings class LoginAPIView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') # 假设这里进行了用户名密码校验 if not authenticate(username=username, password=password): return Response({"error": "Invalid credentials"}, status=400) jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) # 获取 Payload token = jwt_encode_handler(payload) # 编码生 Token return Response({"token": token}) ``` 这段代码实现了用户登录后的 Token 返回逻辑[^3]。它依赖于 DRF-JWT 提供的功能,简化了 Token 的生过程。 --- #### 方法三:基于 Django 默认认证机制 如果不希望引入第三方库,也可以手动管理 Token 并将其存储到数据库中。Django Rest Framework (DRF) 提供了一种简单的方式——`TokenAuthentication`。 ##### 步骤说明: 1. 安装 DRF 后,在设置文件中启用 Token 认证支持。 2. 创建 Token 对象并与用户绑定。 3. 在视图中返回生Token。 下面是具体代码示例: ```python from rest_framework.authtoken.models import Token from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response class ObtainAuthTokenView(APIView): def post(self, request, format=None): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user is None or not user.is_active: return Response({'error': 'Invalid Credentials'}, status=400) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) class ProtectedResourceView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = {'detail': f'Hello {request.user.username}, this is a protected resource.'} return Response(content) ``` 以上代码分别演示了如何获取 Token 和保护资源访问[^5]。 --- #### 测试接口 为了验证 Token 是否正常工作,可以创建一个测试视图如下所示: ```python from django.http import JsonResponse def test_view(request): auth_header = request.META.get('HTTP_AUTHORIZATION', '') if auth_header.startswith('Bearer '): token = auth_header.split()[1] return JsonResponse({'status': 'success', 'token': token}) else: return JsonResponse({'status': 'failure', 'message': 'No valid token provided'}) ``` 该视图会解析请求头中的 Bearer Token,并返回给客户端进行调试[^4]。 --- ### 总结 Django 支持多种 Token方案,可以根据实际需求选择合适的方法。无论是手动生还是借助插件,都需要妥善处理安全性问题,比如设置合理的过期时间、防止泄露等。 问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值