コード例 #1
0
  /**
   * Request token key using Oauth2
   *
   * @param tokenUrl
   * @param clientId
   * @param clientSecret
   * @return tokenkey
   * @throws ParseException
   * @throws IOException
   * @throws OAuthSystemException
   * @throws OAuthProblemException
   */
  public static String Oauth2ClientRequestToken(
      String tokenUrl, String clientId, String clientSecret) throws ParseException, IOException {
    // configure Oauth2 and get access token
    OAuthClientRequest request = null;
    OAuthClient oAuthClient = null;
    OAuthJSONAccessTokenResponse tokenResponse = null;

    try {
      request =
          OAuthClientRequest.tokenLocation(tokenUrl)
              .setClientId(clientId)
              .setClientSecret(clientSecret)
              .setGrantType(GrantType.CLIENT_CREDENTIALS)
              .setScope("all")
              .buildBodyMessage();

      oAuthClient = new OAuthClient(new URLConnectionClient());
      tokenResponse = oAuthClient.accessToken(request, OAuthJSONAccessTokenResponse.class);
    } catch (OAuthSystemException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OAuthProblemException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (tokenResponse == null) return null;

    // return token
    return tokenResponse.getAccessToken();
  }
コード例 #2
0
  /**
   * Get resource using Oauth2, in this case Mendeley API
   *
   * @param tokenUrl
   * @param clientId
   * @param clientSecret
   * @param CatalogUrl
   * @return Jackson JsonNode
   * @throws ParseException
   * @throws IOException
   * @throws OAuthSystemException
   * @throws OAuthProblemException
   */
  public static JsonNode Oauth2ClientRequestCatalog(
      String tokenUrl, String clientId, String clientSecret, String catalogUrl)
      throws ParseException, IOException, OAuthSystemException, OAuthProblemException {
    // configure Oauth2 and get access token
    OAuthClientRequest request =
        OAuthClientRequest.tokenLocation(tokenUrl)
            .setClientId(clientId)
            .setClientSecret(clientSecret)
            .setGrantType(GrantType.CLIENT_CREDENTIALS)
            .setScope("all")
            .buildBodyMessage();
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthJSONAccessTokenResponse tokenResponse =
        oAuthClient.accessToken(request, OAuthJSONAccessTokenResponse.class);

    // get the resources ( authors or publications )
    HttpGet httpGet = new HttpGet(catalogUrl);
    httpGet.setHeader("Authorization", "Bearer " + tokenResponse.getAccessToken());
    DefaultHttpClient apacheHttpClient = ApacheHttpTransport.newDefaultHttpClient();
    HttpResponse httpResponse = apacheHttpClient.execute(httpGet);

    // map the results into jsonMap
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(httpResponse.getEntity().getContent());
  }
コード例 #3
0
ファイル: TraktV2.java プロジェクト: hrk/trakt-java
  /**
   * Request to refresh an expired access token for trakt. If your app is still authorized, returns
   * a response which includes a new access token.
   *
   * <p>Supply the received access token to {@link #setAccessToken(String)} and store the refresh
   * token to later refresh the access token once it has expired.
   *
   * <p>On failure re-authorization of your app is required (see {@link #getAuthorizationRequest}).
   *
   * @param clientId The OAuth client id obtained from trakt.
   * @param clientSecret The OAuth client secret obtained from trakt.
   * @param redirectUri The redirect URI as configured on trakt.
   * @param refreshToken The refresh token obtained with the last access token request response.
   */
  public static OAuthAccessTokenResponse refreshAccessToken(
      String clientId, String clientSecret, String redirectUri, String refreshToken)
      throws OAuthSystemException, OAuthProblemException {
    OAuthClientRequest request =
        getAccessTokenRefreshRequest(clientId, clientSecret, redirectUri, refreshToken);

    OAuthClient client = new OAuthClient(new TraktHttpClient());
    return client.accessToken(request);
  }
コード例 #4
0
  public OAuthPrincipal principal(String accessToken) throws CasOAuthException {

    OAuthPrincipal p = _accessTokenCache.get(accessToken);
    if (p != null) return p;
    try {
      OAuthClientRequest cr =
          new OAuthBearerClientRequest(casServerUrl + "oauth2.0/profile")
              .setAccessToken(accessToken)
              .buildQueryMessage();
      OAuthClient client = new OAuthClient(new URLConnectionClient());
      OAuthResourceResponse cres = client.resource(cr, "GET", OAuthResourceResponse.class);
      String body = cres.getBody();
      p = createJsonPrincipal(body, accessToken);
      _accessTokenCache.put(accessToken, p);
    } catch (Exception e) {
      throw new CasOAuthException("verifyCode", e);
    }
    return p;
  }
コード例 #5
0
  public String verifyCode(String callbackUrl, String code) throws CasOAuthException {
    String accessToken = null;
    try {
      TokenRequestBuilder trb =
          OAuthClientRequest.tokenLocation(casServerUrl + "oauth2.0/accessToken");
      trb.setGrantType(GrantType.AUTHORIZATION_CODE).setCode(code);
      trb.setClientId(clientId).setClientSecret(clientSecret);
      trb.setRedirectURI(callbackUrl);
      if (clientScope != null) trb.setScope(clientScope);
      OAuthClientRequest accReq = trb.buildQueryMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
      GitHubTokenResponse oAuthResponse =
          oAuthClient.accessToken(accReq, GitHubTokenResponse.class);
      accessToken = oAuthResponse.getAccessToken();
      System.out.println("accessToken=" + accessToken);
    } catch (Exception e) {
      throw new CasOAuthException("verifyCode", e);
    }
    return accessToken;
  }
コード例 #6
0
  public OAuthJSONAccessTokenResponse getAccessToken(HttpServletRequest request)
      throws FcConnectException {

    try {
      OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

      log.debug("autorization code" + oar.getCode());

      // vérification a rajouter par rapport au state pour éviter le man in the middle
      //			if (StringUtils.isBlank(stateResponse) ||
      //					!stateResponse.equals(stateFromSession)) {
      //
      //				res = Response.ok("<p>Erreur de verif state response !!</p>",TEXT_HTML);
      //				addCORSOrigin(servletContext,res, headers);
      //		    	return res.build();
      ////				return new RedirectView("/login");
      //			}

      // récupération de l'access token
      OAuthClientRequest authClientRequest =
          OAuthClientRequest.tokenLocation(configuration.getTokenUri())
              .setGrantType(GrantType.AUTHORIZATION_CODE)
              .setClientId(configuration.getClientId())
              .setClientSecret(configuration.getClientSecret())
              .setRedirectURI(configuration.getRedirectUri())
              .setCode(oar.getCode())
              .buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

      return oAuthClient.accessToken(authClientRequest);

    } catch (OAuthSystemException e) {
      throw new FcConnectException("Error during request for accessToken : ", e);
    } catch (OAuthProblemException e) {
      throw new FcConnectException("Error during accessToken retrieving : ", e);
    }
  }
コード例 #7
0
  public String getUserInfo(String accessToken) throws FcConnectException {

    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

    // récupération du profil client
    OAuthClientRequest bearerClientRequest;
    try {
      bearerClientRequest =
          new OAuthBearerClientRequest(configuration.getUserInfoUri())
              .setAccessToken(accessToken)
              .buildHeaderMessage();

      OAuthResourceResponse resourceResponse =
          oAuthClient.resource(
              bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);

      return resourceResponse.getBody();

    } catch (OAuthSystemException e) {
      throw new FcConnectException("Error during userInfo request building : ", e);
    } catch (OAuthProblemException e) {
      throw new FcConnectException("Error during userInfo retrieving : ", e);
    }
  }
  private OAuthClientResponse getOauthResponse(
      OAuthClient oAuthClient, OAuthClientRequest accessRequest)
      throws AuthenticationFailedException {

    OAuthClientResponse oAuthResponse = null;
    try {
      oAuthResponse = oAuthClient.accessToken(accessRequest);
    } catch (OAuthSystemException e) {
      if (log.isDebugEnabled()) {
        log.debug("Exception while requesting access token", e);
      }
      throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (OAuthProblemException e) {
      if (log.isDebugEnabled()) {
        log.debug("Exception while requesting access token", e);
      }
    }
    return oAuthResponse;
  }
コード例 #9
0
  @GET
  @Path("authorize")
  @Produces("text/html")
  public Response authorize(@QueryParam("code") String code, @QueryParam("state") String state)
      throws URISyntaxException {
    String newURI = uriInfo.getBaseUri().toString();
    newURI = newURI.substring(0, newURI.indexOf("webapi"));
    URI uri = null;
    if ((code == null) || code.isEmpty()) {
      uri = UriBuilder.fromUri(new URI(newURI)).path("/").build();
      return Response.seeOther(uri).build();
    }
    try {
      OAuthClientRequest request =
          OAuthClientRequest.tokenProvider(org.apache.oltu.oauth2.common.OAuthProviderType.FACEBOOK)
              .setCode(code)
              .setClientId(env.getFacebookClientId())
              .setClientSecret(env.getFacebookClientSecret())
              .setRedirectURI(
                  UriBuilder.fromUri(uriInfo.getBaseUri())
                      .path(env.getFacebookAuthorizeRoute())
                      .build()
                      .toString())
              .buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
      String token = getAccessToken(request.getBody());
      OAuthClientRequest bearerClientRequest =
          new OAuthBearerClientRequest(env.getFacebookUserInfoUrl())
              .setAccessToken(token)
              .buildQueryMessage();
      OAuthResourceResponse resourceResponse =
          oAuthClient.resource(
              bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
      String userId = getFacebookProfileId(resourceResponse);

      userId = "fb-" + userId;
      if (httpServletRequest.getSession().getAttribute(AuthFilter.USER_ALT_ID_KEY) != null) {
        String sessionUserId =
            (String) httpServletRequest.getSession().getAttribute(AuthFilter.USER_ALT_ID_KEY);
        if (!sessionUserId.contains("fb-")) {
          UserInfo userFromAllIds = userDAO.findFromAllIds(sessionUserId);
          UserInfo userIdFromAllIds = userDAO.findFromAllIds(userId);
          if ((userDAO.containsAuthServiceId(userId, sessionUserId)
                  && ((userFromAllIds == null) || (userIdFromAllIds == null)))
              || ((userFromAllIds != null)
                  && (userIdFromAllIds != null)
                  && !userFromAllIds.getPublicKey().equals(userIdFromAllIds.getPublicKey()))) {
            uri =
                UriBuilder.fromUri(new URI(newURI))
                    .fragment("/users/" + sessionUserId)
                    .build("/", "/users/" + sessionUserId);
            return Response.seeOther(uri).build();
          }
          UserInfo userWithAddId = userDAO.setAdditionalId(userFromAllIds.getPublicKey(), userId);
          if (userWithAddId == null) {
            httpServletRequest.getSession().setAttribute(AuthFilter.USER_ALT_ID_KEY, userId);
            sessionUserId =
                (String) httpServletRequest.getSession().getAttribute(AuthFilter.USER_ALT_ID_KEY);
            uri =
                UriBuilder.fromUri(new URI(newURI))
                    .fragment("/users/" + sessionUserId)
                    .build("/", "/users/" + sessionUserId);
            return Response.seeOther(uri).build();
          }
          state = "profile";
        } else {
          httpServletRequest.getSession().removeAttribute(AuthFilter.USER_ID_KEY);
          httpServletRequest.getSession().removeAttribute(AuthFilter.USER_ALT_ID_KEY);
          return Response.seeOther(uri).build();
        }
      }
      httpServletRequest.getSession().setAttribute(AuthFilter.USER_ALT_ID_KEY, userId);
      UserInfo user = userDAO.findFromAllIds(userId);
      if ((user == null)) {
        user = userDAO.create(userId);
      }
      httpServletRequest.getSession().setAttribute(AuthFilter.USER_ID_KEY, user.getPublicKey());
      if (logScheduler != null) {
        Log log = new Log();
        log.setType(OperationType.LOGIN_LOGOUT);
        log.setUserId(user.getPublicKey());
        String additionalIdsStr = "";
        for (String id : user.getAdditionalIds()) {
          additionalIdsStr += id + ";";
        }
        log.setUserAdditionalIds(additionalIdsStr);
        log.setMachineId(AuthFilter.getMachineId(httpServletRequest));
        log.setLocation(AuthFilter.getUserLocation(httpServletRequest));
        log.setSessionId(httpServletRequest.getSession().getId());
        logScheduler.createLog(log);
      }
      if ("profile".equals(state)) {
        uri =
            UriBuilder.fromUri(new URI(newURI))
                .fragment("/users/" + userId)
                .build("/", "/users/" + userId);
      } else if (!(state == null) && !state.isEmpty()) {
        uri = UriBuilder.fromUri(new URI(newURI)).fragment(state).build("", state);
      } else {
        uri = UriBuilder.fromUri(new URI(newURI)).path("/").build();
      }

    } catch (OAuthSystemException | OAuthProblemException e) {
      throw new WebApplicationException(e);
    } catch (MalformedURLException e) {
      throw new WebApplicationException(e);
    } catch (IOException e) {
      throw new WebApplicationException(e);
    }
    return Response.seeOther(uri).build();
  }