com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OicSession.java    From oic-auth-plugin with MIT License 6 votes vote down vote up
/**
 * When the identity provider is done with its thing, the user comes back here.
 * @return an {@link HttpResponse}
 */
public HttpResponse doFinishLogin(StaplerRequest request)  {
    StringBuffer buf = request.getRequestURL();
    if (request.getQueryString() != null) {
        buf.append('?').append(request.getQueryString());
    }
    AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString());
    if (!state.equals(responseUrl.getState())) {
        return new Failure("State is invalid");
    }
    String code = responseUrl.getCode();
    if (responseUrl.getError() != null) {
        return new Failure(
                "Error from provider: " + responseUrl.getError() + ". Details: " + responseUrl.getErrorDescription()
        );
    } else if (code == null) {
        return new Failure("Missing authorization code");
    } else {
        return onSuccess(code);
    }
}
 
Example #2
Source File: OAuth2CallbackServlet.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestUrl = req.getRequestURL().append('?').append(req.getQueryString()).toString();
    AuthorizationCodeResponseUrl authorizationCodeResponseUrl =
            new AuthorizationCodeResponseUrl(requestUrl);

    if (authorizationCodeResponseUrl.getError() != null) {
        throw new IOException("Received error: " + authorizationCodeResponseUrl.getError());
    } else {
        // Authenticate the user and store their credential with their user ID (derived from
        // the request).
        HttpSession httpSession = req.getSession(true);
        if (httpSession.getAttribute(Server.USER_SESSION_ID) == null) {
            httpSession.setAttribute(Server.USER_SESSION_ID, new Random().nextLong());
        }
        String authorizationCode = authorizationCodeResponseUrl.getCode();
        oAuth2Credentials.authenticate(authorizationCode, httpSession.getAttribute(Server.USER_SESSION_ID).toString());
    }
    resp.sendRedirect("/");
}
 
Example #3
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private String getUserFromUrl(AuthorizationCodeResponseUrl authorizationCodeResponseUrl)
    throws IOException {
  String state = authorizationCodeResponseUrl.getState();
  if (!(state == null || state.isEmpty())) {
    String decoded = URLDecoder.decode(state, "UTF-8");
    String[] items = decoded.split("&");
    for (String str : items) {
      if (str.startsWith("userId=")) {
        return str.substring(7, str.length());
      }
    }
  }
  return null;
}
 
Example #4
Source File: Oauth2CallbackServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Handles an error to the authorization, such as when an end user denies authorization. */
@Override
protected void onError(
    HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
    throws ServletException, IOException {
  resp.getWriter().print("<p>You Denied Authorization.</p>");
  resp.setStatus(200);
  resp.addHeader("Content-Type", "text/html");
}
 
Example #5
Source File: AbstractAuthorizationCodeCallbackServlet.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  StringBuffer buf = req.getRequestURL();
  if (req.getQueryString() != null) {
    buf.append('?').append(req.getQueryString());
  }
  AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString());
  String code = responseUrl.getCode();
  if (responseUrl.getError() != null) {
    onError(req, resp, responseUrl);
  } else if (code == null) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    resp.getWriter().print("Missing authorization code");
  } else {
    lock.lock();
    try {
      if (flow == null) {
        flow = initializeFlow();
      }
      String redirectUri = getRedirectUri(req);
      TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
      String userId = getUserId(req);
      Credential credential = flow.createAndStoreCredential(response, userId);
      onSuccess(req, resp, credential);
    } finally {
      lock.unlock();
    }
  }
}
 
Example #6
Source File: OAuthServletCallback.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException {
	// handle error
	log.debug("erreur");
}
 
Example #7
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Process callback request.
 *
 * @param requestUrl request URI. URI should contain authorization code generated by authorization
 *     server
 * @param scopes specify exactly what type of access needed. This list must be exactly the same as
 *     list passed to the method {@link #getAuthenticateUrl(URL, java.util.List)}
 * @return id of authenticated user
 * @throws OAuthAuthenticationException if authentication failed or <code>requestUrl</code> does
 *     not contain required parameters, e.g. 'code'
 */
public String callback(URL requestUrl, List<String> scopes) throws OAuthAuthenticationException {
  if (!isConfigured()) {
    throw new OAuthAuthenticationException(AUTHENTICATOR_IS_NOT_CONFIGURED);
  }

  AuthorizationCodeResponseUrl authorizationCodeResponseUrl =
      new AuthorizationCodeResponseUrl(requestUrl.toString());
  final String error = authorizationCodeResponseUrl.getError();
  if (error != null) {
    throw new OAuthAuthenticationException("Authentication failed: " + error);
  }
  final String code = authorizationCodeResponseUrl.getCode();
  if (code == null) {
    throw new OAuthAuthenticationException("Missing authorization code. ");
  }

  try {
    TokenResponse tokenResponse =
        flow.newTokenRequest(code)
            .setRequestInitializer(
                request -> {
                  if (request.getParser() == null) {
                    request.setParser(flow.getJsonFactory().createJsonObjectParser());
                  }
                  request.getHeaders().setAccept(MediaType.APPLICATION_JSON);
                })
            .setRedirectUri(findRedirectUrl(requestUrl))
            .setScopes(scopes)
            .execute();
    String userId = getUserFromUrl(authorizationCodeResponseUrl);
    if (userId == null) {
      userId =
          getUser(newDto(OAuthToken.class).withToken(tokenResponse.getAccessToken())).getId();
    }
    flow.createAndStoreCredential(tokenResponse, userId);
    return userId;
  } catch (IOException ioe) {
    throw new OAuthAuthenticationException(ioe.getMessage());
  }
}
 
Example #8
Source File: AbstractAuthorizationCodeCallbackServlet.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Handles an error to the authorization, such as when an end user denies authorization.
 *
 * <p>
 * Default implementation is to do nothing, but subclasses should override and implement. Sample
 * implementation:
 * </p>
 *
 * <pre>
    resp.sendRedirect("/denied");
 * </pre>
 *
 * @param req HTTP servlet request
 * @param resp HTTP servlet response
 * @param errorResponse error response ({@link AuthorizationCodeResponseUrl#getError()} is not
 *        {@code null})
 * @throws ServletException HTTP servlet exception
 * @throws IOException some I/O exception
 */
protected void onError(
    HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
    throws ServletException, IOException {
}