java后端服务调用googleapi直接获取accesstoekn

java后端服务调⽤googleapi直接获取accesstoekn
开发google api 的时候遇到的问题  需要维护google上的搜索商品    google  需要获取access token 才能正常调⽤
相关⽂档
⽹上看了很多相关⽂章  没有直接获取access  token的  ⼤部分都是需要  url  重定向  取URL⾥⾯的code  然后⽤code取access  token 服务端这样处理⽐较难  应该是直接调⼀个接⼝返回  access  token  这样处理⽐较⽅便
前⾯的步骤简单说⼀下
1.创建服务项⽬
2.⽣成加密⽂件  (json或者p12)
这两个步骤⽹上都有教程
双环戊二烯获取access token
⽅式⼀  直接⽤google原⽣的api
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = wTrustedTransport();
JsonFactory jsonFactory = DefaultInstance();
GoogleCredentials credential = GoogleCredentials.fromStream(ResourceAsStream("加密的json⽂件路径"))
.createScoped(Arrays.asList("leapis/auth/userinfo.profile",
"leapis/auth/content"));//设置作⽤域
String accessToken = AccessToken().getTokenValue();
System.out.println(accessToken);
ComputeCredential computeCredential = new ComputeCredential(httpTransport,jsonFactory);
computeCredential.setAccessToken(accessToken);
ShoppingContent service = new ShoppingContent
.Builder(httpTransport, jsonFactory, computeCredential)
.build();
ShoppingContent.Products.List productList = service.products().list(BigInteger.valueOf(110141822));
ProductsListResponse page = ute();
List<Product> resources = Resources();
System.out.String());
//插⼊和更新
//        service.products().insert(BigInteger.valueOf(110141822),new Product());
//
/
/        //批量插⼊和更新
//        ProductsCustomBatchRequest productsCustomBatchRequest = new ProductsCustomBatchRequest();
//        List<ProductsCustomBatchRequestEntry> updates = new ArrayList();
//        ProductsCustomBatchRequestEntry info = new ProductsCustomBatchRequestEntry();
//        info.setProduct(new Product());
//        productsCustomBatchRequest.setEntries(updates);
//        service.products().custombatch(productsCustomBatchRequest);
}
⽅式⼆  ⽣成jwt字符串  再掉接⼝取access  token
a.使⽤ jjwt ⽅式⽣成JWT
private static String getJwt() throws InvalidKeyException {
String private_key = getPrivateKey(); //json⽂件中的private_key  记得删除 头和尾的不必要字符串        long now = System.currentTimeMillis() / 1000;
Map<String, Object> heads = new HashMap();
heads.put("typ", "JWT");
heads.put("alg", "RS256");
System.out.JSONString(heads));
Claims claims = Jwts.claims();
claims.put("iss", "content-api@iconic-vine-270102.iam.gserviceaccount");
claims.put("scope", "leapis/auth/content");
claims.put("aud", "leapis/token");
claims.put("exp", now + 3600 + "");
claims.put("iat", now + "");
System.out.JSONString(claims));
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
byte[] apikeys = DatatypeConverter.parseBase64Binary(private_key);
Key key = wKey(apikeys);
大庆油田宽带String str = Jwts.builder()
.setHeader(heads)
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)) //token保留的时间                .signWith(signatureAlgorithm, key) //
pact();
System.out.println(str);
越南全民皆兵return str;
}
public static String getPrivateKey(){
String jsonStr = "";
try {
File jsonFile = new File("加密json问价路径");
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = ad()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return JSON.parseObject(jsonStr).get("private_key").toString().replace("-----BEGIN PRIVATE KEY-----\n", "").replace("\n-----END PRIVATE KEY-----\n", "");
} catch (IOException e) {
e.printStackTrace();
return null;
名师帮你赢高考}
}
b.⾕歌原⽣api⽣成jwt
private static String getJwt() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = wTrustedTransport();
JsonFactory jsonFactory = DefaultInstance();
GoogleCredential credential = GoogleCredential.fromStream(ResourceAsStream("加密json⽂件路径"));        ateScoped(Collections.singleton(ShoppingContentScopes.CONTENT));
PrivateKey privateKey = ServiceAccountPrivateKey();
long now = System.currentTimeMillis() / 1000;
JsonWebSignature.Header header = new JsonWebSignature.Header();
header.put("typ", "JWT");
header.put("alg", "RS256");
System.out.JSONString(header));
JsonWebToken.Payload payload = new JsonWebSignature.Payload();
payload.put("iss", "content-api@iconic-vine-270102.iam.gserviceaccount");
payload.put("scope", "leapis/auth/content");
payload.put("aud", "leapis/token");
payload.put("exp", now + 3600);
payload.put("iat", now);
System.out.JSONString(payload));
String s = JsonWebSignature.signUsingRsaSha256(privateKey, jsonFactory, header, payload);
System.out.println(s);
return s;
}
97gab
google  根据jwt  ⽣成  access  token 的接⼝
post请求  form表单形式提交参数
grant_type    urn:ietf:params:oauth:grant-type:jwt-bearer  (固定写法) assertion  jwt字符串
pom相关
<dependencies>
<dependency>
<groupId&le.apis</groupId>
<artifactId>google-api-services-oauth2</artifactId>
<version>v2-rev20200213-1.30.9</version>
</dependency>
<dependency>
<groupId&le.apis</groupId>
<artifactId>google-api-services-content</artifactId>
<version>v2.1-rev20200219-1.30.9</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId&le.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.34.2</version>
</dependency>
<dependency>
<groupId&le.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.30.6</version>
</dependency>
<dependency>
<groupId&le.oauth-client</groupId>
<artifactId>google-oauth-client-servlet</artifactId>
<version>1.30.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
食品价格连续上涨
<groupId&le.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.30.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId&le.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>            <version>0.20.0</version>
</dependency>
</dependencies>
千万注意账户对应权限  如果对应不上会导致很奇怪的问题

本文发布于:2024-09-21 20:27:04,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/501718.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:需要   问题   对应   搜索
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议