net.oauth.OAuthServiceProvider Java Examples

The following examples show how to use net.oauth.OAuthServiceProvider. 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: DataApiOAuthServlet.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Inject
public DataApiOAuthServlet(@Named("request_token_path") String requestTokenPath,
    @Named("authorize_token_path") String authorizeTokenPath,
    @Named("access_token_path") String accessTokenPath,
    @Named("all_tokens_path") String allTokensPath,
    OAuthServiceProvider serviceProvider,
    OAuthValidator validator, DataApiTokenContainer tokenContainer,
    SessionManager sessionManager, TokenGenerator tokenGenerator) {
  this.requestTokenPath = requestTokenPath;
  this.authorizeTokenPath = authorizeTokenPath;
  this.accessTokenPath = accessTokenPath;
  this.allTokensPath = allTokensPath;
  this.serviceProvider = serviceProvider;
  this.validator = validator;
  this.tokenContainer = tokenContainer;
  this.sessionManager = sessionManager;
  this.tokenGenerator = tokenGenerator;
  this.xsrfTokens =
      CacheBuilder.newBuilder()
        .expireAfterWrite(XSRF_TOKEN_TIMEOUT_HOURS, TimeUnit.HOURS)
        .<ParticipantId, String>build().asMap();
}
 
Example #2
Source File: DataApiOAuthServlet.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@Inject
public DataApiOAuthServlet(@Named("request_token_path") String requestTokenPath,
    @Named("authorize_token_path") String authorizeTokenPath,
    @Named("access_token_path") String accessTokenPath,
    @Named("all_tokens_path") String allTokensPath,
    OAuthServiceProvider serviceProvider,
    OAuthValidator validator, DataApiTokenContainer tokenContainer,
    SessionManager sessionManager, TokenGenerator tokenGenerator) {
  this.requestTokenPath = requestTokenPath;
  this.authorizeTokenPath = authorizeTokenPath;
  this.accessTokenPath = accessTokenPath;
  this.allTokensPath = allTokensPath;
  this.serviceProvider = serviceProvider;
  this.validator = validator;
  this.tokenContainer = tokenContainer;
  this.sessionManager = sessionManager;
  this.tokenGenerator = tokenGenerator;
  this.xsrfTokens =
      CacheBuilder.newBuilder()
        .expireAfterWrite(XSRF_TOKEN_TIMEOUT_HOURS, TimeUnit.HOURS)
        .<ParticipantId, String>build().asMap();
}
 
Example #3
Source File: DefaultOAuthStoreTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetConsumerKeyAndSecret() throws Exception {
    OAuthConsumerStore consumerStore = new OAuthConsumerStoreImpl();
    consumerStore.setGadgetUri(GADGET_URI);
    consumerStore.setConsumerKey("gadgetConsumer");
    consumerStore.setConsumerSecret(CONSUMER_SECRET);
    consumerStore.setKeyType(OAuthConsumerStore.KeyType.HMAC_SYMMETRIC);
    OAuthServiceProvider provider = new OAuthServiceProvider(null, null, null);

    expect(consumerStoreService.findByUriAndServiceName(GADGET_URI, SERVICE_NAME))
            .andReturn(consumerStore);
    replay(consumerStoreService);

    final OAuthStore.ConsumerInfo keyAndSecret =
            oAuthStore.getConsumerKeyAndSecret(token, SERVICE_NAME, provider);
    assertNotNull(keyAndSecret);
    assertEquals(OAuth.HMAC_SHA1, keyAndSecret.getConsumer().getProperty(
            OAuth.OAUTH_SIGNATURE_METHOD));

    verify(consumerStoreService);

}
 
Example #4
Source File: OAuthServiceImplRobotTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
private OAuthAccessor buildAccessor(String consumerKey,
  String consumerSecret, String requestTokenUrl, String authorizeUrl,
  String callbackUrl, String accessTokenUrl) {
  OAuthServiceProvider provider =
    new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer =
    new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  return accessor;
}
 
Example #5
Source File: GoolgeOAuthParamVO.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
public GoolgeOAuthParamVO(String cONSUMER_KEY, String cONSUMER_SECRET, String requestTokenURL, String userAuthorizationURL,
		String accessTokenURL, String scope, String userInfo) {
	super();
	CONSUMER_KEY = cONSUMER_KEY;
	CONSUMER_SECRET = cONSUMER_SECRET;
	this.oAuthServiceProvider = new OAuthServiceProvider(requestTokenURL, userAuthorizationURL, accessTokenURL);
	this.scope = scope;
	this.userInfo = userInfo;
}
 
Example #6
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  validator = mock(OAuthValidator.class);
  sessionManager = mock(SessionManager.class);

  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getLocale()).thenReturn(Locale.ENGLISH);
  HttpSession sessionMock = mock(HttpSession.class);
  when(req.getSession()).thenReturn(sessionMock);
  when(req.getSession(anyBoolean())).thenReturn(sessionMock);

  resp = mock(HttpServletResponse.class);
  outputStream = new ServletOutputStreamStub();
  when(resp.getOutputStream()).thenReturn(outputStream);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  servlet =
      new DataApiOAuthServlet(REQUEST_TOKEN_PATH,
          AUTHORIZE_TOKEN_PATH, ACCESS_TOKEN_PATH, GET_ALL_TOKENS_PATH,
          serviceProvider, validator, tokenContainer, sessionManager, tokenGenerator);
}
 
Example #7
Source File: DataApiServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  converterManager = mock(EventDataConverterManager.class);
  waveletProvider = mock(WaveletProvider.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  validator = mock(OAuthValidator.class);
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com"));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));
  when(req.getMethod()).thenReturn("POST");

  resp = mock(HttpServletResponse.class);
  stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);
  when(resp.getWriter()).thenReturn(writer);

  servlet =
      new DataApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, validator, tokenContainer);
}
 
Example #8
Source File: DataApiTokenContainerTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  container = new DataApiTokenContainer(tokenGenerator);
  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);
}
 
Example #9
Source File: ActiveApiServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  validator = mock(OAuthValidator.class);

  EventDataConverterManager converterManager = mock(EventDataConverterManager.class);
  WaveletProvider waveletProvider = mock(WaveletProvider.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  OAuthServiceProvider oAuthServiceProvider = mock(OAuthServiceProvider.class);
  AccountStore accountStore = mock(AccountStore.class);

  when(accountStore.getAccount(ROBOT)).thenReturn(
      new RobotAccountDataImpl(ROBOT, "", "secret", null, true));

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getHeaderNames()).thenReturn(
      convertRawEnumerationToGeneric(new StringTokenizer("Authorization")));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));

  resp = mock(HttpServletResponse.class);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  servlet =
      new ActiveApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, oAuthServiceProvider, validator, accountStore);
}
 
Example #10
Source File: RobotApiModule.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
protected OAuthServiceProvider provideOAuthServiceProvider(Config config) {
    String publicAddress = config.getString("core.http_frontend_public_address");
  // Three urls, first is to get an unauthorized request token, second is to
  // authorize the request token, third is to exchange the authorized request
  // token with an access token.
  String requestTokenUrl = getOAuthUrl(publicAddress, REQUEST_TOKEN_PATH);
  String authorizeTokenUrl = getOAuthUrl(publicAddress, AUTHORIZE_TOKEN_PATH);
  String accessTokenUrl = getOAuthUrl(publicAddress, ACCESS_TOKEN_PATH);

  return new OAuthServiceProvider(requestTokenUrl, authorizeTokenUrl, accessTokenUrl);
}
 
Example #11
Source File: ActiveApiServlet.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Inject
public ActiveApiServlet(RobotSerializer robotSerializer,
    EventDataConverterManager converterManager, WaveletProvider waveletProvider,
    @Named("ActiveApiRegistry") OperationServiceRegistry operationRegistry,
    ConversationUtil conversationUtil, OAuthServiceProvider oAuthServiceProvider,
    OAuthValidator validator, AccountStore accountStore) {
  super(robotSerializer, converterManager, waveletProvider, operationRegistry, conversationUtil,
      validator);
  this.oauthServiceProvider = oAuthServiceProvider;
  this.accountStore = accountStore;
}
 
Example #12
Source File: OAuth.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Performs 3-legged OAuth authorization through Data API.
 *
 * @param service wave service.
 */
public String threeLeggedOAuth(WaveService service) throws IOException {
  Console.println("Paste this URL in your browser:\n" + serverUrl + GET_ALL_TOKENS_URL_POSTFIX);
  Console.println("Type the code you received here: ");
  String authorizationCode = new String(
      Base64.decodeBase64(Console.readLine().getBytes("UTF-8")), "UTF-8");

  StringTokenizer st = new StringTokenizer(authorizationCode);

  String requestToken = st.nextToken();
  String accessToken = st.nextToken();
  String tokenSecret = st.nextToken();

  String requestUrl = serverUrl + REQUEST_URL_POSTFIX;
  String authUrl = serverUrl + AUTH_URL_POSTFIX;
  String accessUrl = serverUrl + ACCESS_URL_POSTFIX;

  OAuthServiceProvider provider = new OAuthServiceProvider(requestUrl
      + "?scope=" + URLEncoder.encode("", "utf-8"), authUrl, accessUrl);
  OAuthConsumer consumer = new OAuthConsumer("", THREE_LEGGED_API_CONSUMER_KEY,
      THREE_LEGGED_API_CONSUMER_SECRET, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  accessor.requestToken = requestToken;
  accessor.accessToken = accessToken;
  accessor.tokenSecret = tokenSecret;

  String rpcServerUrl = serverUrl + DATA_API_RPC_URL_POSTFIX;
  service.setupOAuth(accessor, rpcServerUrl);
  return rpcServerUrl;
}
 
Example #13
Source File: DefaultOAuthStore.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ConsumerInfo getConsumerKeyAndSecret(SecurityToken securityToken, String serviceName,
                                            OAuthServiceProvider provider) throws GadgetException {
    String gadgetUri = securityToken.getAppUrl();
    OAuthConsumerStore consumerStore = consumerStoreService.findByUriAndServiceName(gadgetUri, serviceName);
    if (consumerStore == null) {
        return null;
    }
    OAuthConsumer consumer = createOAuthConsumer(provider, consumerStore);
    String callbackUrl = (consumerStore.getCallbackUrl() != null ?
            consumerStore.getCallbackUrl() : defaultCallbackUrl);

    return new ConsumerInfo(consumer, consumerStore.getKeyName(), callbackUrl);
}
 
Example #14
Source File: OAuthServiceImplRobotTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
private OAuthAccessor buildAccessor(String consumerKey,
  String consumerSecret, String requestTokenUrl, String authorizeUrl,
  String callbackUrl, String accessTokenUrl) {
  OAuthServiceProvider provider =
    new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer =
    new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  return accessor;
}
 
Example #15
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  validator = mock(OAuthValidator.class);
  sessionManager = mock(SessionManager.class);

  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getLocale()).thenReturn(Locale.ENGLISH);
  HttpSession sessionMock = mock(HttpSession.class);
  when(req.getSession()).thenReturn(sessionMock);
  when(req.getSession(anyBoolean())).thenReturn(sessionMock);

  resp = mock(HttpServletResponse.class);
  outputStream = new ServletOutputStreamStub();
  when(resp.getOutputStream()).thenReturn(outputStream);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  servlet =
      new DataApiOAuthServlet(REQUEST_TOKEN_PATH,
          AUTHORIZE_TOKEN_PATH, ACCESS_TOKEN_PATH, GET_ALL_TOKENS_PATH,
          serviceProvider, validator, tokenContainer, sessionManager, tokenGenerator);
}
 
Example #16
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  converterManager = mock(EventDataConverterManager.class);
  waveletProvider = mock(WaveletProvider.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  validator = mock(OAuthValidator.class);
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com"));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));
  when(req.getMethod()).thenReturn("POST");

  resp = mock(HttpServletResponse.class);
  stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);
  when(resp.getWriter()).thenReturn(writer);

  servlet =
      new DataApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, validator, tokenContainer);
}
 
Example #17
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  container = new DataApiTokenContainer(tokenGenerator);
  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);
}
 
Example #18
Source File: ActiveApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  validator = mock(OAuthValidator.class);

  EventDataConverterManager converterManager = mock(EventDataConverterManager.class);
  WaveletProvider waveletProvider = mock(WaveletProvider.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  OAuthServiceProvider oAuthServiceProvider = mock(OAuthServiceProvider.class);
  AccountStore accountStore = mock(AccountStore.class);

  when(accountStore.getAccount(ROBOT)).thenReturn(
      new RobotAccountDataImpl(ROBOT, "", "secret", null, true));

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getHeaderNames()).thenReturn(
      convertRawEnumerationToGeneric(new StringTokenizer("Authorization")));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));

  resp = mock(HttpServletResponse.class);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  servlet =
      new ActiveApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, oAuthServiceProvider, validator, accountStore);
}
 
Example #19
Source File: RobotApiModule.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
protected OAuthServiceProvider provideOAuthServiceProvider(Config config) {
    String publicAddress = config.getString("core.http_frontend_public_address");
  // Three urls, first is to get an unauthorized request token, second is to
  // authorize the request token, third is to exchange the authorized request
  // token with an access token.
  String requestTokenUrl = getOAuthUrl(publicAddress, REQUEST_TOKEN_PATH);
  String authorizeTokenUrl = getOAuthUrl(publicAddress, AUTHORIZE_TOKEN_PATH);
  String accessTokenUrl = getOAuthUrl(publicAddress, ACCESS_TOKEN_PATH);

  return new OAuthServiceProvider(requestTokenUrl, authorizeTokenUrl, accessTokenUrl);
}
 
Example #20
Source File: ActiveApiServlet.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Inject
public ActiveApiServlet(RobotSerializer robotSerializer,
    EventDataConverterManager converterManager, WaveletProvider waveletProvider,
    @Named("ActiveApiRegistry") OperationServiceRegistry operationRegistry,
    ConversationUtil conversationUtil, OAuthServiceProvider oAuthServiceProvider,
    OAuthValidator validator, AccountStore accountStore) {
  super(robotSerializer, converterManager, waveletProvider, operationRegistry, conversationUtil,
      validator);
  this.oauthServiceProvider = oAuthServiceProvider;
  this.accountStore = accountStore;
}
 
Example #21
Source File: OAuth.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Performs 3-legged OAuth authorization through Data API.
 *
 * @param service wave service.
 */
public String threeLeggedOAuth(WaveService service) throws IOException {
  Console.println("Paste this URL in your browser:\n" + serverUrl + GET_ALL_TOKENS_URL_POSTFIX);
  Console.println("Type the code you received here: ");
  String authorizationCode = new String(
      Base64.decodeBase64(Console.readLine().getBytes("UTF-8")), "UTF-8");

  StringTokenizer st = new StringTokenizer(authorizationCode);

  String requestToken = st.nextToken();
  String accessToken = st.nextToken();
  String tokenSecret = st.nextToken();

  String requestUrl = serverUrl + REQUEST_URL_POSTFIX;
  String authUrl = serverUrl + AUTH_URL_POSTFIX;
  String accessUrl = serverUrl + ACCESS_URL_POSTFIX;

  OAuthServiceProvider provider = new OAuthServiceProvider(requestUrl
      + "?scope=" + URLEncoder.encode("", "utf-8"), authUrl, accessUrl);
  OAuthConsumer consumer = new OAuthConsumer("", THREE_LEGGED_API_CONSUMER_KEY,
      THREE_LEGGED_API_CONSUMER_SECRET, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  accessor.requestToken = requestToken;
  accessor.accessToken = accessToken;
  accessor.tokenSecret = tokenSecret;

  String rpcServerUrl = serverUrl + DATA_API_RPC_URL_POSTFIX;
  service.setupOAuth(accessor, rpcServerUrl);
  return rpcServerUrl;
}
 
Example #22
Source File: TokenRequestController.java    From cxf with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/tokenRequest")
protected ModelAndView handleRequest(@ModelAttribute("oAuthParams") OAuthParams oAuthParams,
                                     HttpServletRequest request)
    throws Exception {

    String oauthToken = oAuthParams.getOauthToken();

    String tokenRequestEndpoint = oAuthParams.getTokenRequestEndpoint();
    String clientID = oAuthParams.getClientID();

    if (tokenRequestEndpoint == null || "".equals(tokenRequestEndpoint)) {
        oAuthParams.setErrorMessage("Missing token request URI");
    }

    if (clientID == null || "".equals(clientID)) {
        oAuthParams.setErrorMessage("Missing consumer key");
    }

    if (oauthToken == null || "".equals(oauthToken)) {
        oAuthParams.setErrorMessage("Missing oauth token");
    }

    String verifier = oAuthParams.getOauthVerifier();
    if (verifier == null || "".equals(verifier)) {
        oAuthParams.setErrorMessage("Missing oauth verifier");
    }

    if (oAuthParams.getErrorMessage() == null) {
        OAuthClient client = new OAuthClient(new URLConnectionClient());
        OAuthServiceProvider provider = new OAuthServiceProvider(
            oAuthParams.getTemporaryCredentialsEndpoint(),
            oAuthParams.getResourceOwnerAuthorizationEndpoint(), tokenRequestEndpoint);

        OAuthConsumer consumer = new OAuthConsumer(null, clientID,
            oAuthParams.getClientSecret(),
            provider);
        OAuthAccessor accessor = new OAuthAccessor(consumer);
        accessor.requestToken = oauthToken;
        accessor.tokenSecret = Common.findCookieValue(request, "tokenSec");

        Map<String, String> parameters = new HashMap<>();
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, oAuthParams.getSignatureMethod());
        parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
        parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
        parameters.put(OAuth.OAUTH_TOKEN, oauthToken);
        parameters.put(OAuth.OAUTH_VERIFIER, oAuthParams.getOauthVerifier());


        try {
            client.getAccessToken(accessor, OAuthMessage.GET, parameters.entrySet());
            oAuthParams.setOauthToken(accessor.accessToken);
        } catch (Exception e) {
            oAuthParams.setErrorMessage(e.toString());
            oAuthParams.setOauthToken(oauthToken);
            return new ModelAndView("tokenRequest");
        }
        oAuthParams.setOauthTokenSecret(accessor.tokenSecret);
    }

    oAuthParams.setClientID(Common.findCookieValue(request, "clientID"));
    oAuthParams.setClientSecret(Common.findCookieValue(request, "clientSecret"));

    return new ModelAndView("accessToken");
}
 
Example #23
Source File: GetProtectedResourceController.java    From cxf with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/getProtectedResource")
protected ModelAndView handleRequest(@ModelAttribute("oAuthParams") OAuthParams oAuthParams,
                                     HttpServletRequest request)
    throws Exception {

    OAuthServiceProvider provider = new OAuthServiceProvider(
        oAuthParams.getTemporaryCredentialsEndpoint(),
        oAuthParams.getResourceOwnerAuthorizationEndpoint(), null);

    OAuthConsumer consumer = new OAuthConsumer(null, oAuthParams.getClientID(),
        oAuthParams.getClientSecret(),
        provider);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.requestToken = oAuthParams.getOauthToken();
    accessor.tokenSecret = oAuthParams.getOauthTokenSecret();

    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, oAuthParams.getSignatureMethod());
    parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
    parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
    parameters.put(OAuth.OAUTH_TOKEN, oAuthParams.getOauthToken());
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, oAuthParams.getClientID());

    OAuthMessage msg = null;
    String method = request.getParameter("op");


    if ("GET".equals(method)) {
        msg = accessor
            .newRequestMessage(OAuthMessage.GET, oAuthParams.getGetResourceURL(), parameters.entrySet());
    } else {
        msg = accessor
            .newRequestMessage(OAuthMessage.POST, oAuthParams.getPostResourceURL(),
                parameters.entrySet());
    }


    OAuthClient client = new OAuthClient(new URLConnectionClient());

    msg = client.access(msg, ParameterStyle.QUERY_STRING);

    StringBuilder bodyBuffer = readBody(msg);

    oAuthParams.setResourceResponse(bodyBuffer.toString());
    String authHeader = msg.getHeader("WWW-Authenticate");
    String oauthHeader = msg.getHeader("OAuth");
    String header = "";

    if (authHeader != null) {
        header += "WWW-Authenticate:" + authHeader;
    }

    if (oauthHeader != null) {
        header += "OAuth:" + oauthHeader;
    }

    oAuthParams.setHeader(header);
    oAuthParams.setResponseCode(((OAuthResponseMessage)msg).getHttpResponse().getStatusCode());

    return new ModelAndView("accessToken");
}
 
Example #24
Source File: OAuthServiceImpl.java    From incubator-retired-wave with Apache License 2.0 3 votes vote down vote up
/**
 * Factory method. Initializes OAuthServiceProvider with necessary tokens and
 * urls.
 * 
 * @param userRecordKey key consisting of user id and wave id.
 * @param consumerKey service provider OAuth consumer key.
 * @param consumerSecret service provider OAuth consumer secret.
 * @param requestTokenUrl url to get service provider request token.
 * @param authorizeUrl url to service provider authorize page.
 * @param callbackUrl url to callback page.
 * @param accessTokenUrl url to get service provider access token.
 * @return OAuthService instance.
 */
public static OAuthService newInstance(String userRecordKey, String consumerKey,
    String consumerSecret, String requestTokenUrl, String authorizeUrl, String callbackUrl,
    String accessTokenUrl) {
  OAuthServiceProvider provider =
      new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer = new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  OAuthClient client = new OAuthClient(new OpenSocialHttpClient());
  PersistenceManagerFactory pmf = SingletonPersistenceManagerFactory.get();
  return new OAuthServiceImpl(accessor, client, pmf, userRecordKey);
}
 
Example #25
Source File: OAuthServiceImpl.java    From swellrt with Apache License 2.0 3 votes vote down vote up
/**
 * Factory method. Initializes OAuthServiceProvider with necessary tokens and
 * urls.
 * 
 * @param userRecordKey key consisting of user id and wave id.
 * @param consumerKey service provider OAuth consumer key.
 * @param consumerSecret service provider OAuth consumer secret.
 * @param requestTokenUrl url to get service provider request token.
 * @param authorizeUrl url to service provider authorize page.
 * @param callbackUrl url to callback page.
 * @param accessTokenUrl url to get service provider access token.
 * @return OAuthService instance.
 */
public static OAuthService newInstance(String userRecordKey, String consumerKey,
    String consumerSecret, String requestTokenUrl, String authorizeUrl, String callbackUrl,
    String accessTokenUrl) {
  OAuthServiceProvider provider =
      new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer = new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  OAuthClient client = new OAuthClient(new OpenSocialHttpClient());
  PersistenceManagerFactory pmf = SingletonPersistenceManagerFactory.get();
  return new OAuthServiceImpl(accessor, client, pmf, userRecordKey);
}