本文整理汇总了Java中com.google.api.client.googleapis.auth.oauth2.GoogleIdToken类的典型用法代码示例。如果您正苦于以下问题:Java GoogleIdToken类的具体用法?Java GoogleIdToken怎么用?Java GoogleIdToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
GoogleIdToken类属于com.google.api.client.googleapis.auth.oauth2包,在下文中一共展示了GoogleIdToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: authenticate
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
@Override
public boolean authenticate(HttpServletRequest request) {
// Preserve current check for App Engine Env.
if (EnvUtil.isRunningOnAppEngine()) {
return APPENGINE_PEER.equals(request.getHeader(HEADER_APPENGINE_PEER));
}
// Skip peer verification for localhost request.
if (localHostAddresses.contains(request.getRemoteAddr())) {
logger.fine("Skip endpoints peer verication from localhost.");
return true;
}
// Verify peer token, signer and audience.
GoogleIdToken idToken =
jwtAuthenticator.verifyToken(request.getHeader(HEADER_PEER_AUTHORIZATION));
if (idToken == null || !SIGNER.equals(idToken.getPayload().getEmail())
|| !matchHostAndPort(idToken, request)) {
return false;
}
return true;
}
示例2: verify
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
@Override
public boolean verify(GoogleIdToken googleIdToken) throws GeneralSecurityException, IOException {
// check the payload
if (!((IdTokenVerifier)this).verify(googleIdToken)) {
return false;
}
// verify signature
for (PublicKey publicKey : getPublicKeysManager().getPublicKeys()) {
try {
if (googleIdToken.verifySignature(publicKey)) {
return true;
}
} catch (Exception e) {
System.err.println("Verify Token:" + e);
}
}
return false;
}
示例3: checkToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
/**
* Validate a token used to access the backend
*
* @param tokenString
* id token sent from client
* @return Payload for this token or null if invalid
*/
public static GoogleIdToken.Payload checkToken(String tokenString)
throws UnauthorizedException {
// TODO: validate auth token, client id, etc.
AuthChecker checker = new AuthChecker(
UniversalConstants.APP_CLIENT_IDS, Constants.WEB_CLIENT_ID);
try {
GoogleIdToken.Payload payload = checker.check(tokenString);
if (checker.isValid() || AppConfig.isTest()) {
return payload;
} else {
throw new UnauthorizedException("Invalid Auth With Problem: "
+ checker.problem());
}
} catch (GeneralSecurityException e) {
// TODO: flag the security error
throw new UnauthorizedException("Security Error: "
+ e.getLocalizedMessage());
}
}
示例4: getAuthorizedUserForPayload
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
/**
* Get ZeppaUser based on GoogleIdToken payload
*
* @param payload
* @return
*/
public static ZeppaUser getAuthorizedUserForPayload(GoogleIdToken.Payload payload) throws UnauthorizedException {
// Verify it is valid
if (payload == null || !Utils.isWebSafe(payload.getEmail())) {
throw new UnauthorizedException("Invalid id-token");
}
// This will be the result of the query or null
ZeppaUser result = null;
// Execute the query and clean up where necessary
PersistenceManager mgr = getPersistenceManager();
try {
Query q = mgr.newQuery(ZeppaUser.class, "authEmail == '" + payload.getEmail() + "'");
q.setUnique(true);
result = (ZeppaUser) q.execute();
} finally {
mgr.close();
}
return result;
}
示例5: checkToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
/**
* Validate a token used to access the backend
*
* @param tokenString
* id token sent from client
* @return Payload for this token or null if invalid
*/
public static GoogleIdToken.Payload checkToken(String tokenString) throws UnauthorizedException {
// TODO: validate auth token, client id, etc.
AuthChecker checker = new AuthChecker(UniversalConstants.APP_CLIENT_IDS, Constants.WEB_CLIENT_ID);
try {
GoogleIdToken.Payload payload = checker.check(tokenString);
if (checker.isValid() || AppConfig.isTest()) {
return payload;
} else {
throw new UnauthorizedException("Invalid Auth With Problem: " + checker.problem());
}
} catch (GeneralSecurityException e) {
// TODO: flag the security error
throw new UnauthorizedException("Security Error: " + e.getLocalizedMessage());
}
}
示例6: checkTestAuthToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
/**
* Return a Google Id Token payload for the purpose of testing
*
* @param authToken
* - "token" ;)
* @return payload for this test email
*/
private GoogleIdToken.Payload checkTestAuthToken(String tokenString) {
GoogleIdToken.Payload payload = null;
if (Utils.isWebSafe(tokenString)
&& tokenString.startsWith(TestUtils.getTestTokenPrefix())) {
// parse the auth email out of the "token"
String authEmail = tokenString.substring(TestUtils
.getTestTokenPrefixLength());
payload = new GoogleIdToken.Payload();
payload.setEmail(authEmail);
payload.setEmailVerified(true);
// Expire in an hour (like other token payloads)
payload.setExpirationTimeSeconds(System.currentTimeMillis()
+ (60 * 60 * 1000));
}
return payload;
}
示例7: authenticate
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
@Override
public Optional<User> authenticate(String idToken) throws AuthenticationException {
try {
return Optional.ofNullable(tokenVerifier.verify(idToken))
.map(GoogleIdToken::getPayload)
.filter(payload -> hostedDomain == null
|| payload.getHostedDomain().equals(hostedDomain))
.map(this::payloadToUser);
} catch (GeneralSecurityException | IOException e) {
throw new AuthenticationException(e);
}
}
示例8: auth
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
private static AuthContext auth(RequestContext requestContext) {
final Request request = requestContext.request();
final boolean hasAuthHeader = request.header(HttpHeaders.AUTHORIZATION).isPresent();
if (!hasAuthHeader) {
return Optional::empty;
}
final String authHeader = request.header(HttpHeaders.AUTHORIZATION).get();
if (!authHeader.startsWith(BEARER_PREFIX)) {
throw new ResponseException(Response.forStatus(Status.BAD_REQUEST
.withReasonPhrase("Authorization token must be of type Bearer")));
}
final GoogleIdToken googleIdToken;
try {
final String token = authHeader.substring(BEARER_PREFIX.length());
googleIdToken = verifyIdToken(token);
} catch (IllegalArgumentException e) {
throw new ResponseException(Response.forStatus(Status.BAD_REQUEST
.withReasonPhrase("Failed to parse Authorization token")), e);
}
if (googleIdToken == null) {
throw new ResponseException(Response.forStatus(Status.UNAUTHORIZED
.withReasonPhrase("Authorization token is invalid")));
}
return () -> Optional.of(googleIdToken);
}
示例9: verifyToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
@VisibleForTesting
GoogleIdToken verifyToken(String token) {
if (token == null) {
return null;
}
try {
return verifier.verify(token);
} catch (GeneralSecurityException | IOException | IllegalArgumentException e) {
logger.warning(e.getMessage());
return null;
}
}
示例10: matchHostAndPort
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
private boolean matchHostAndPort(GoogleIdToken idToken, HttpServletRequest request) {
URL urlFromIdToken;
URL urlFromRequest;
try {
urlFromIdToken = new URL((String) idToken.getPayload().getAudience());
urlFromRequest = new URL(request.getRequestURL().toString());
return urlFromIdToken.getHost().equals(urlFromRequest.getHost())
&& getPort(urlFromIdToken) == getPort(urlFromRequest);
} catch (MalformedURLException e) {
logger.warning("Invalid URL from request");
return false;
}
}
示例11: processGoogleReturn
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
private void processGoogleReturn(String code, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Verifier verifier = new Verifier(code);
Token accessToken = googleOAuthservice.getAccessToken(null, verifier);
if (accessToken != null) {
// Now we decrypt and Verify the JWT
Checker checker = new Checker(new String[]{EnvironmentUtils.getInstance().getGoogleApiKey()}, EnvironmentUtils.getInstance().getGoogleApiKey());
GoogleIdToken.Payload jwt = checker.check(accessToken.getToken());
if (jwt != null) {
String email = jwt.getEmail();
req.getSession().setAttribute("email", email);
AmazonDynamoDBDAO dao = AmazonDynamoDBDAO.getInstance();
Account account = dao.accountsGetAccount(email);
if (account == null) {
ServletUtils.setFeedback(req, false,EnvironmentUtils.ACCOUNTS_LOCKED);
GoogleAnalyticsHelper.RecordAsyncEvent(SecurityHelper.generateEncryptedId("locked"),GoogleAnalyticsHelper.CATEGORY_USER,GoogleAnalyticsHelper.ACTION_READ_ONLY,"","");
} else {
req.getSession().setAttribute("account", account);
List<Domain> domains = dao.domainsGetDomainsByToken(account.getAccountToken());
req.getSession().setAttribute("domains", domains);
// PLACE THE UPDATED ITEM INTO THE SESSION CACHE
if (EnvironmentUtils.isDynamoSessionCache()) {
AmazonDynamoDBDAO.getInstance().sessionsCreateSession(req.getSession().getId(), account.getEmail(), ServletUtils.getAddressFromRequest(req));
}
GoogleAnalyticsHelper.RecordAsyncEvent(SecurityHelper.generateEncryptedId(account.getEmail()),GoogleAnalyticsHelper.CATEGORY_USER,GoogleAnalyticsHelper.ACTION_LOGIN_GOOGLE,"","");
}
this.getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
return;
}
}
// WE GET HERE ITS BAD
this.getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
}
示例12: getAuthorizedEmployeeForPayload
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
/**
* Get ZeppaUser based on GoogleIdToken payload
*
* @param payload
* @return
*/
public static Employee getAuthorizedEmployeeForPayload(
GoogleIdToken.Payload payload) throws UnauthorizedException {
// Verify it is valid
if (payload == null || !Utils.isWebSafe(payload.getEmail())) {
throw new UnauthorizedException("Invalid id-token");
}
// This will be the result of the query or null
Employee result = null;
// Execute the query and clean up where necessary
PersistenceManager mgr = getPersistenceManager();
try {
Query q = mgr.newQuery(Employee.class,
"emailAddress == '" + payload.getEmail() + "'");
q.setUnique(true);
result = (Employee) q.execute();
} finally {
mgr.close();
}
return result;
}
示例13: tokenSignIn
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
@RequestMapping(value = "/tokensignin", method = RequestMethod.POST)
public void tokenSignIn(@RequestParam("token") String token, HttpServletResponse response)
throws GeneralSecurityException, IOException {
final NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
final JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Collections.singletonList(oauthClientId))
.build();
final GoogleIdToken googleIdToken = verifier.verify(token);
if (googleIdToken == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
final Payload payload = googleIdToken.getPayload();
final Boolean emailVerified = payload.getEmailVerified();
if (emailVerified) {
final String login = userDetailDao.getUserLoginByEmail(payload.getEmail());
if (StringUtils.isNotEmpty(login)) {
final UserAuthView userDetails = userDetailDao.getUserAuthView(login);
final Authentication auth =
new UsernamePasswordAuthenticationToken(userDetails,
null,
userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
response.setStatus(HttpServletResponse.SC_OK);
} else {
response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
}
}
}
示例14: getUserByIdToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
public User getUserByIdToken(String idTokenString) throws GeneralSecurityException, IOException, IllegalArgumentException, ObjectNotFoundException, NdexException {
ApacheHttpTransport.Builder builder = new ApacheHttpTransport.Builder();
GoogleIdTokenVerifier localVerifier = new GoogleIdTokenVerifier.Builder(builder.build(), new JacksonFactory())
.setAudience(Collections.singletonList(clientID))
// Or, if multiple clients access the backend:
//.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
.build();
GoogleIdToken idToken = localVerifier.verify(idTokenString);
if (idToken != null) {
Payload payload = idToken.getPayload();
// Print user identifier
// String userId = payload.getSubject();
// System.out.println("User ID: " + userId);
// Get profile information from payload
String email = payload.getEmail();
/* boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name"); */
try (UserDAO userDao = new UserDAO()) {
User user = userDao.getUserByEmail(email.toLowerCase(),true);
return user;
} catch ( SQLException e1) {
e1.printStackTrace();
throw new UnauthorizedOperationException("SQL Error when getting user by email: " + e1.getMessage());
}
}
throw new UnauthorizedOperationException("Invalid OAuth ID token.");
}
示例15: getUserUUIDByIdToken
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; //导入依赖的package包/类
public UUID getUserUUIDByIdToken(String idTokenString) throws GeneralSecurityException, IOException, IllegalArgumentException, ObjectNotFoundException, NdexException {
ApacheHttpTransport.Builder builder = new ApacheHttpTransport.Builder();
GoogleIdTokenVerifier localVerifier = new GoogleIdTokenVerifier.Builder(builder.build(), new JacksonFactory())
.setAudience(Collections.singletonList(clientID))
// Or, if multiple clients access the backend:
//.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
.build();
GoogleIdToken idToken = localVerifier.verify(idTokenString);
if (idToken != null) {
Payload payload = idToken.getPayload();
// Print user identifier
String userId = payload.getSubject();
System.out.println("User ID: " + userId);
// Get profile information from payload
String email = payload.getEmail();
try (UserDAO userDao = new UserDAO()) {
UUID userUUID = userDao.getUUIDByEmail(email.toLowerCase());
return userUUID;
} catch ( SQLException e1) {
e1.printStackTrace();
throw new UnauthorizedOperationException("SQL Error when getting user by email: " + e1.getMessage());
}
}
throw new UnauthorizedOperationException("Invalid OAuth ID token.");
}