我正在按照下一个教程来保护我的 Rest 服务。
但是我对步骤Verify Token Fields有疑问,首先我不知道我的依赖项是否正确:
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.13.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>1.13.1-beta</version>
</dependency>
其次,当我在示例中使用 Checker 类时,在调用中 Verifier.verify(token)
它返回false,这是因为在类GoogleIdTokenVerifier
中 Set clientIds为空。我一步一步按照教程,我完全迷路了
谢谢大家。
编辑:这是我现在使用的代码,它似乎正在工作:
public class Checker {
private final String mAudience;
private final Lock lock = new ReentrantLock();
private final GoogleIdTokenVerifier mVerifier;
private final JsonFactory mJFactory;
private String mProblem = "Verification failed. (Time-out?)";
private final List<String> mClientIDs;
private List<PublicKey> publicKeys;
private final Clock clock;
NetHttpTransport transport;
private long expirationTimeMilliseconds;
public Checker(String[] clientIDs, String audience) {
mClientIDs = Arrays.asList(clientIDs);
mAudience = audience;
transport = new NetHttpTransport();
mJFactory = new GsonFactory();
mVerifier = new GoogleIdTokenVerifier(transport, mJFactory);
clock = Clock.SYSTEM;
}
public GoogleIdToken.Payload check(String tokenString) {
GoogleIdToken.Payload payload = null;
try {
GoogleIdToken token = GoogleIdToken.parse(mJFactory, tokenString);
if (checkSignature(mClientIDs.get(0), token)) {
GoogleIdToken.Payload tempPayload = token.getPayload();
if (!tempPayload.getAudience().equals(mAudience))
mProblem = "Audience mismatch";
else if (!mClientIDs.contains(tempPayload.getIssuee()))
mProblem = "Client ID mismatch";
else
payload = tempPayload;
}
} catch (GeneralSecurityException e) {
mProblem = "Security issue: " + e.getLocalizedMessage();
} catch (IOException e) {
mProblem = "Network problem: " + e.getLocalizedMessage();
} catch (Exception e) {
mProblem = "Problem: " + e.getLocalizedMessage();
}
return payload;
}
public String problem() {
return mProblem;
}
boolean checkSignature(String clientIds, GoogleIdToken idToken)
throws GeneralSecurityException, IOException {
JsonWebSignature.Header header = idToken.getHeader();
String algorithm = header.getAlgorithm();
if (algorithm.equals("RS256")) {
lock.lock();
try {
if (publicKeys == null
|| clock.currentTimeMillis() + 300000 > expirationTimeMilliseconds) {
mVerifier.loadPublicCerts();
publicKeys = mVerifier.getPublicKeys();
expirationTimeMilliseconds = mVerifier
.getExpirationTimeMilliseconds();
}
Signature signer = Signature.getInstance("SHA256withRSA");
for (PublicKey publicKey : publicKeys) {
signer.initVerify(publicKey);
signer.update(idToken.getSignedContentBytes());
if (signer.verify(idToken.getSignatureBytes())) {
return true;
}
}
} finally {
lock.unlock();
}
}
return false;
}
}