当前位置: 首页>>代码示例>>Java>>正文


Java GoogleIdTokenVerifier.verify方法代码示例

本文整理汇总了Java中com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier.verify方法的典型用法代码示例。如果您正苦于以下问题:Java GoogleIdTokenVerifier.verify方法的具体用法?Java GoogleIdTokenVerifier.verify怎么用?Java GoogleIdTokenVerifier.verify使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier的用法示例。


在下文中一共展示了GoogleIdTokenVerifier.verify方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: tokenSignIn

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的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);
        }
    }
}
 
开发者ID:kTT,项目名称:adjule,代码行数:37,代码来源:UserAuthEndpoint.java

示例2: getUserByIdToken

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的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.");
	
}
 
开发者ID:ndexbio,项目名称:ndex-rest,代码行数:39,代码来源:GoogleOpenIDAuthenticator.java

示例3: getUserUUIDByIdToken

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的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.");
	
	
}
 
开发者ID:ndexbio,项目名称:ndex-rest,代码行数:35,代码来源:GoogleOpenIDAuthenticator.java

示例4: verify

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的package包/类
private GoogleIdToken verify(String idTokenString) throws GeneralSecurityException, IOException
{
	List<String> audience = Collections.singletonList(authenticationSettings.getGoogleAppClientId());
	GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder(
			googlePublicKeysManager).setAudience(audience).build();
	return googleIdTokenVerifier.verify(idTokenString);
}
 
开发者ID:molgenis,项目名称:molgenis,代码行数:8,代码来源:GoogleAuthenticationProcessingFilter.java

示例5: parseGoogleAccountFromIdToken

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的package包/类
private static GoogleAccount parseGoogleAccountFromIdToken(String clientId, String idTokenString) {
	Preconditions.notEmptyString(clientId, "OAuth client ID should be provided.");
	Preconditions.notEmptyString(idTokenString, "IdToken should be provided.");

	GoogleIdTokenVerifier oldVerifier = new GoogleIdTokenVerifier.Builder(getDefaultHttpTransport(), getDefaultJsonFactory())
			.setAudience(Collections.singletonList(clientId))
			// For Android Play Services older than 8.3 and web client
			.setIssuer("accounts.google.com")
			.build();

	GoogleIdTokenVerifier newVerifier = new GoogleIdTokenVerifier.Builder(getDefaultHttpTransport(), getDefaultJsonFactory())
			.setAudience(Collections.singletonList(clientId))
			// For Android Play Services newer than 8.3
			.setIssuer("https://accounts.google.com")
			.build();

	GoogleIdToken idToken;
	try {
		idToken = oldVerifier.verify(idTokenString);
		if (idToken == null) {
			idToken = newVerifier.verify(idTokenString);
		}
	} catch (Exception e) {
		LOGGER.error(e.getMessage(), e);
		return null;
	}
	if (idToken == null) {
		LOGGER.warn(String.format("Invalid or expired Google ID token: %s", idTokenString));
		return null;
	}

	Payload payload = idToken.getPayload();
	for (Entry<String, Object> entry : payload.entrySet()) {
		LOGGER.trace(String.format("%s=%s", entry.getKey(), entry.getValue()));
	}

	return idTokenPayloadToGoogleAccount(payload);
}
 
开发者ID:sgr-io,项目名称:social-signin,代码行数:39,代码来源:GoogleSignInService.java

示例6: processRegistration

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; //导入方法依赖的package包/类
@Deprecated
@CrossOrigin(origins="*", maxAge=3600)
   @RequestMapping(value="/tokensigningoogle_deprecated", method = RequestMethod.POST, headers = "content-type=application/x-www-form-urlencoded")
   public String processRegistration(@RequestParam("idtoken") String idTokenString) //, ModelMap model)
           throws GeneralSecurityException, IOException {
	logger.info("Doing tokensigningoogle");
       GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
               .setAudience(Arrays.asList(environment.getRequiredProperty("google.client_id"))).setIssuer("accounts.google.com").build();

       GoogleIdToken idToken = verifier.verify(idTokenString);
       if (idToken != null) {
           Payload payload = idToken.getPayload();
           // Print user identifier
           String userId = payload.getSubject();
           // Get profile information from payload
           String email = payload.getEmail();
           logger.info("Logged in " + userId + " " + email);
           boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
           //List<User> users = DbFunction.listHqlNew("FROM User WHERE email = :email", "email", email);

           if (!emailVerified ) { //|| users.isEmpty()) {
               return "/error.html";
           } else {
               //List<String> roles = DbFunction.listSQLNew(
               //        "SELECT role.name FROM user_role_association JOIN role ON role.id = role_id JOIN user on user.id = user_id WHERE user.email = :email",
               //        "email", email);

               List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
               //for (String role : roles) {
               //    authorities.add(new SimpleGrantedAuthority(role));
               //}
               authorities.add(new SimpleGrantedAuthority("USER_AUTH0RITY"));

               UserDetails userDetails = new org.springframework.security.core.userdetails.User(userId,
                               "xxy", true, true, true, true, authorities);
               Authentication authentication = new UsernamePasswordAuthenticationToken(userId, null,
                       userDetails.getAuthorities());
               //UserDetails userDetails = new org.springframework.security.core.userdetails.User(users.get(0).getName(),
               //        "xx", users.get(0).isEnabled(), true, true, true, authorities);
               //Authentication authentication = new UsernamePasswordAuthenticationToken(users.get(0).getName(), null,
               //        userDetails.getAuthorities());
               SecurityContextHolder.clearContext();
               SecurityContextHolder.getContext().setAuthentication(authentication);
               httpSession.setAttribute("sch", userDetails);
       	    logger.info("first check " + httpSession.getAttribute("sch"));

               return "/browsing/databases";
           }
       } else {
           System.out.println("Invalid ID token.");
       }
       return "/error.html";
   }
 
开发者ID:DiscourseDB,项目名称:discoursedb-core,代码行数:54,代码来源:BrowsingRestController.java


注:本文中的com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier.verify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。