由IOS端传过来code
服务端代码
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class AppleLoginController {
/**
* 苹果授权登录
*
* @param code
* @param subject
* @return
* @throws Exception
*/
@GetMapping(“/authCode”)
public void authCode(String code) throws Exception {
String client_id = “com.**.**”; // 被授权的APP ID
Map<String, Object> header = new HashMap<String, Object>();
header.put(“kid”, “***”); // 参考后台配置
Map<String, Object> claims = new HashMap<String, Object>();
claims.put(“iss”, “***”); // 参考后台配置 team id
long now = System.currentTimeMillis() / 1000;
claims.put(“iat”, now);
claims.put(“exp”, now + 86400 * 30); // *长半年,单位秒
claims.put(“aud”, “https://appleid.apple.com”); // 默认值
claims.put(“sub”, client_id);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readKey());
KeyFactory keyFactory = KeyFactory.getInstance(“EC”);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
String client_secret = Jwts.builder().setHeader(header).setClaims(claims)
.signWith(SignatureAlgorithm.ES256, privateKey).compact();
String url = “https://appleid.apple.com/auth/token”;
// POST 请求
Map<String, String> params = new HashMap<String, String>();
Map<String, String> headers = new HashMap<String, String>();
headers.put(“Content-Type”, “application/x-www-form-urlencoded”);
params.put(“client_id”, client_id);
params.put(“client_secret”, client_secret);
params.put(“code”, code);
params.put(“grant_type”, “authorization_code”);
params.put(“redirect_uri”, “”);
HttpClientResult httpClientResult = HttpClientUtil.doPost(url, headers, params);
Map<String, Object> jsonObject = JSONObject.parseObject(httpClientResult.getContent());
DecodedJWT jwtString = JWT.decode(jsonObject.get(“id_token”).toString());
String sub = jwtString.getSubject();
}
private byte[] readKey() throws Exception {
String temp = “*******”;//记得去掉换行符号,密钥
return Base64.getDecoder().decode(temp);
}
}
jar包依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<!– https://mvnrepository.com/artifact/com.auth0/java-jwt –>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>