I have this error:
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Exception : No authentication header information
I am using GWT with eclipse.
I really don't know what's wrong in my code.
Any help would be appreciated.
Thanks in advance.
Client side EntryPoint class:
private static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
private static final String GOOGLE_CLIENT_ID = "xxxxxxx.apps.googleusercontent.com";
private static final String CONTACTS_SCOPE = "https://www.google.com/m8/feeds";
private static final Auth AUTH = Auth.get();
public void onModuleLoad() {
final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID).withScopes(CONTACTS_SCOPE);
AUTH.login(req, new Callback<String, Throwable>() {
public void onSuccess(String token) {
ABASession.setToken(token);
}
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
I store the token in a class that I will use later.
Server side: ContactServiceImpl (RPC GAE procedure)
//The token stored previously is then passed through RPC
public List printAllContacts(String token) {
try {
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey("My consumer key");
oauthParameters.setOAuthConsumerSecret("My consumer secret");
PrivateKey privKey = getPrivateKey("certificate/akyosPrivateKey.key");
OAuthRsaSha1Signer signer = new OAuthRsaSha1Signer(privKey);
ContactsService service = new ContactsService("XXX");
service.setProtocolVersion(ContactsService.Versions.V3);
oauthParameters.setOAuthToken(token);
service.setOAuthCredentials(oauthParameters, signer);
// Request the feed
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/default/full?xoauth_requestor_id=xxx.yyy#gmail.com");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
for (Email email : entry.getEmailAddresses()) {
contactNames.add(email.getAddress());
}
}
return contactNames;
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
}
return null;
}
set the scope
oauthParameters.setScope("http://www.google.com/m8/feeds/contacts/default/full");
Related
I run a custom WebSocketServlet for Jetty, which sends short text push notifications (for an async mobile and desktop word game) to many platforms (Facebook, Vk.com, Mail.ru, Ok.ru also Firebase and Amazon messaging) using a Jetty HttpClient instance:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
#Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
This has worked very good for the past year, but since I have recently upgraded my WAR-file to use Jetty 9.4.14.v20181114 the trouble has begun -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
Suddenly the getContentAsString method called for successful HttpClient invocations started to deliver the strings, which were fetched previously - prepended to the the actual result string.
What could it be please, is it some changed BufferingResponseListener behaviour or maybe some non-obvious Java quirk?
BufferingResponseListener was never intended to be reusable across requests.
Just allocate a new BufferingResponseListener for every request/response.
I do not want to use a generated SDK for my API Gateway endpoint. I want to use the plain AWS SDK. When I googled how to do that, nothing obvious came up in the first few hits (surprisingly). So I cobbled this together:
private static void invokeApiGatewayWithCognito(String identityPoolId, String endpoint) throws URISyntaxException {
AmazonCognitoIdentity cognitoClient = AmazonCognitoIdentityClient.builder()
.withCredentials(new AWSCredentialsProvider() {
#Override
public AWSCredentials getCredentials() {
return new AnonymousAWSCredentials();
}
#Override
public void refresh() {
}
}).withRegion(EU_CENTRAL_1.getName()).build();
String identityId = cognitoClient.getId(new GetIdRequest()
.withIdentityPoolId(identityPoolId))
.getIdentityId();
Credentials cognitoCreds = cognitoClient
.getCredentialsForIdentity(
new GetCredentialsForIdentityRequest()
.withIdentityId(identityId))
.getCredentials();
AWS4Signer signer = new AWS4Signer();
signer.setServiceName("execute-api");
signer.setRegionName(EU_CENTRAL_1.getName());
AmazonHttpClient amazonHttpClient =
new AmazonHttpClient(new ClientConfiguration());
Request r = new DefaultRequest("execute-api");
r.setEndpoint(new URI(endpoint));
r.setHttpMethod(HttpMethodName.GET);
BasicSessionCredentials basicCreds = new BasicSessionCredentials(
cognitoCreds.getAccessKeyId(),
cognitoCreds.getSecretKey(),
cognitoCreds.getSessionToken());
signer.sign(r, basicCreds);
amazonHttpClient
.requestExecutionBuilder()
.request(r)
.execute(logResponse());
}
private static HttpResponseHandler<Void> logResponse() {
return new HttpResponseHandler<Void>() {
#Override
public Void handle(HttpResponse httpResponse) throws Exception {
System.out.println("response code = " + httpResponse.getStatusCode());
System.out.println("response headers = " + httpResponse.getHeaders());
System.out.println("response content = " + new String(bytes(httpResponse.getContent())));
return null;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
};
}
It works, but boy is that ugly code. What am I missing? How can this be done more cleanly?
Major edit: 2015-05-27: After some degree of success updated on where I'm currently stuck rather than leaving a rambling post....could really do with some pointers on this one - a little bogged down....
I'm running some code on a Linux app server (WebSphere) that needs to authenticate to an IIS web service which is configured for "Integrated Authentication", but I'm having some problems forming the Authorization: Negotiate token.
I should also say that I need to put this token into the HTTP header for a JAX-WS SOAP request that I will subsequently build. I know my SOAP request itself works because we were using WS-Security Username token profile previously and it worked fine - trying to swap to kerberos is proving difficult...
My problem is with initSecContext I think. It appears that on the first call the context is configured in "some" way and there is some returned token data, but .isEstablished is false. The problem I'm having is putting the initSecContext call into a loop - it seems IIS just closes the connection when I do this. Can anyone give me some pointers - I seem to be taking the approach used by other posters and the Oracle samples (although the IBM/WebSphere sample only makes a single initSecContext call and doesn't check .isEstablished which seems odd to me based on the Oracle documentation).
Anyway, the error I get is below (note the Ready: property seems to clearly say initSecContext needs to loop - to me at least);
[5/27/15 6:51:11:605 UTC] 0000004f SystemOut O INFO: com.mycorp.kerberosKerberosTokenGenerator/getKerberosToken/run: After initSecContext:
--- GSSContext ---
Owner: domainuser#MYDOMAIN.COM
Peer: HTTP/iishost.mycorp.com
State: initialized
Lifetime: indefinite
Ready: no
Flags:
Confidentiality off
Delegation on
Integrity off
MutualAuthn on
ReplayDetection off
SequenceDetection off
DelegatedCred: unknown
--- End of GSSContext ---
[5/27/15 6:51:11:605 UTC] 0000004f SystemOut O INFO: com.mycorp.kerberosKerberosTokenGenerator/getKerberosToken/run: Context is not established, trying again
[5/27/15 6:51:11:606 UTC] 0000004f SystemOut O ERROR: com.mycorp.kerberosKerberosTokenGenerator/getKerberosToken/run: IOException during context establishment: Connection reset
My code is below;
LoginContext lc = getLoginContext(contextName);
final Subject subject = lc.getSubject();
String b64Token = (String) Subject.doAs(subject, new PrivilegedExceptionAction() {
#Override
public Object run() throws PrivilegedActionException, GSSException {
// Create socket to server
Socket socket;
DataInputStream inStream = null;
DataOutputStream outStream = null;
try {
socket = new Socket("iishost.mycorp.com", 443);
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
System.out.println("Exception setting up server sockets: " + ex.getMessage());
}
GSSName gssName = manager.createName(userName, GSSName.NT_USER_NAME, KRB5_MECH_OID);
GSSCredential gssCred = manager.createCredential(gssName.canonicalize(KRB5_MECH_OID),
GSSCredential.DEFAULT_LIFETIME,
KRB5_MECH_OID,
GSSCredential.INITIATE_ONLY);
gssCred.add(gssName, GSSCredential.INDEFINITE_LIFETIME,
GSSCredential.INDEFINITE_LIFETIME,
SPNEGO_MECH_OID,
GSSCredential.INITIATE_ONLY);
GSSName gssServerName = manager.createName(servicePrincipal, KERBEROS_V5_PRINCIPAL_NAME);
GSSContext clientContext = manager.createContext(gssServerName.canonicalize(SPNEGO_MECH_OID),
SPNEGO_MECH_OID,
gssCred,
GSSContext.DEFAULT_LIFETIME);
clientContext.requestCredDeleg(true);
clientContext.requestMutualAuth(true);
byte[] token = new byte[0];
while (!clientContext.isEstablished()) {
try {
token = clientContext.initSecContext(token, 0, token.length);
// IF I LOOK AT token HERE THERE IS CERTAINLY TOKEN DATA THERE - .isEstablished IS STILL FALSE
outStream.writeInt(token.length);
outStream.write(token);
outStream.flush();
// Check if we're done
if (!clientContext.isEstablished()) {
token = new byte[inStream.readInt()];
inStream.readFully(token);
}
} catch (IOException ex) {
// THIS EXCEPTION IS THROWN ON SECOND ITERATION - LOOKS LIKE IIS CLOSES THE CONNECTION
System.out.println("IOException during context establishment: " + ex.getMessage());
}
}
String b64Token = Base64.encode(token);
clientContext.dispose(); // I'm assuming this won't invalidate the token in some way as I need to use it later
return b64Token;
}
});
This doc tells me I don't need to loop on initSecContext, but .isEstablished returns false for me: http://www-01.ibm.com/support/knowledgecenter/SS7K4U_8.5.5/com.ibm.websphere.zseries.doc/ae/tsec_SPNEGO_token.html?cp=SS7K4U_8.5.5%2F1-3-0-20-4-0&lang=en
The Oracle docs tell me I should: https://docs.oracle.com/javase/7/docs/api/org/ietf/jgss/GSSContext.html
My only hesitation is that from the Oracle docs it seems like I'm starting the application conversation, but what I'm trying to do it obtain the token only & it's later on in my code when I will use JAX-WS to post my actual web service call (including the spnego/kerberos token in the http header) - is this the cause of my issue?
Just an update. I have this working now - my previous code was largely ok - it was just my understanding of how the Kerberos token would be added to the JAX-WS request. Turns out it's just a matter of attaching a Handler to the bindingProvider. The handler then obtains the Kerberos token and adds it to the header of the request - nice and easy.
Below is my working Handler which is added to the Handler chain obtained from a call to bindingProvider.getBinding().getHandlerChain()
public class HTTPKerberosHandler implements SOAPHandler<SOAPMessageContext> {
private final String contextName;
private final String servicePrincipal;
private static Oid KRB5_MECH_OID = null;
private static Oid SPNEGO_MECH_OID = null;
private static Oid KERBEROS_V5_PRINCIPAL_NAME = null;
final String className = this.getClass().getName();
static {
try {
KERBEROS_V5_PRINCIPAL_NAME = new Oid("1.2.840.113554.1.2.2.1");
KRB5_MECH_OID = new Oid("1.2.840.113554.1.2.2");
SPNEGO_MECH_OID = new Oid("1.3.6.1.5.5.2");
} catch (final GSSException ex) {
System.out.println("Exception creating mechOid's: " + ex.getMessage());
ex.printStackTrace();
}
}
public HTTPKerberosHandler(final String contextName, final String servicePrincipal) {
this.contextName = contextName;
this.servicePrincipal = servicePrincipal;
}
#Override
public Set<QName> getHeaders() {
return null;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
return false;
}
#Override
public void close(MessageContext context) {
// No action
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
if (((Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY))) {
return handleRequest(context);
} else {
return handleResponse(context);
}
}
private boolean handleRequest(SOAPMessageContext context) {
byte[] token = getKerberosToken(contextName, servicePrincipal);
HashMap<String, String> sendTransportHeaders = new HashMap<String, String>();
sendTransportHeaders.put("Authorization", "Negotiate " + Base64.encode(token));
context.put(com.ibm.websphere.webservices.Constants.REQUEST_TRANSPORT_PROPERTIES, sendTransportHeaders);
return true;
}
private boolean handleResponse(SOAPMessageContext context) {
logger.logInformation(className, "handleResponse", "Inbound response detected");
return true;
}
public byte[] getKerberosToken(final String contextName, final String servicePrincipal) {
try {
LoginContext lc = getLoginContext(contextName);
final Subject subject = lc.getSubject();
byte[] token = (byte[]) Subject.doAs(subject, new PrivilegedExceptionAction() {
#Override
public Object run() throws PrivilegedActionException, GSSException {
final String methodName = "getKerberosToken/run";
final GSSManager manager = GSSManager.getInstance();
Set<Principal> principals = subject.getPrincipals();
Iterator it = principals.iterator();
String principalName = ((Principal) it.next()).getName();
logger.logInformation(className, methodName, "Using principal: [" + principalName + "]");
GSSName gssName = manager.createName(principalName, GSSName.NT_USER_NAME, KRB5_MECH_OID);
GSSCredential gssCred = manager.createCredential(gssName.canonicalize(KRB5_MECH_OID),
GSSCredential.DEFAULT_LIFETIME,
KRB5_MECH_OID,
GSSCredential.INITIATE_ONLY);
gssCred.add(gssName, GSSCredential.INDEFINITE_LIFETIME,
GSSCredential.INDEFINITE_LIFETIME,
SPNEGO_MECH_OID,
GSSCredential.INITIATE_ONLY);
logger.logInformation(className, methodName, "Client TGT obtained: " + gssCred.toString());
GSSName gssServerName = manager.createName(servicePrincipal, GSSName.NT_USER_NAME);
GSSContext clientContext = manager.createContext(gssServerName.canonicalize(SPNEGO_MECH_OID),
SPNEGO_MECH_OID,
gssCred,
GSSContext.DEFAULT_LIFETIME);
logger.logInformation(className, methodName, "Service ticket obtained: " + clientContext.toString());
byte[] token = new byte[0];
token = clientContext.initSecContext(token, 0, token.length);
clientContext.dispose();
return token;
}
});
return token;
} catch (PrivilegedActionException ex) {
logger.logError(HTTPKerberosHandler.class.getName(), methodName, "PrivilegedActionException: " + ex.getMessage());
} catch (Exception ex) {
logger.logError(HTTPKerberosHandler.class.getName(), methodName, "Exception: " + ex.getMessage());
}
return null;
}
private LoginContext getLoginContext(String contextName) {
LoginContext lc = null;
try {
lc = new LoginContext(contextName);
lc.login();
} catch (LoginException le) {
logger.logError(HTTPKerberosHandler.class.getName(), methodName, "Login exception: [" + le.getMessage() + "]");
le.printStackTrace();
}
return lc;
}
}
I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}
When I execute a CalendarService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); I get an OAuthException 401 Error Unknown authorization header.
I'm using GWT+GAE I don't know why I'm receiving this error, oauthParameters seem to be OK.
I get user login on
loginService.login
I check if I have
the authentication already on
oauthService.checkOauthTokenSecret
If not, I'll do a redirect to Google
Aproval page for GCalendar
permission
I get querystring
returned by Google and I get Access
Token and Access Token Secret and
set it to the user entity for later
use on oauthService.upgradeLogin.
And trying to get calendars on
oauthService.getPublicCalendars.
I'm using MVP pattern with mvp4g framework, sorry if is a bit confusing 0:-)
Any idea why I'm receiving 401 error? I think is something about I'm going up & down through client and server and external pages... and something is missing :-( but all parameters seem to be correctly fullfilled.
Client side
public void onStart(){
GWT.log("onStart");
loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
Common.loginInfo = result;
if(Common.loginInfo.isLoggedIn()) {
oauthService.checkOauthTokenSecret(new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
if (result == null){
eventBus.OauthLogin();
}else{
oauthService.upgradeLogin(Window.Location.getQueryString(),Common.loginInfo, new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
Common.loginInfo = result;
getCitas();
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}else{
eventBus.LoadLogin();
}
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}
Server Side
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rdt.citas.client.OAuthoritzationService;
import com.rdt.citas.client.shared.LoginInfo;
public class OAuthoritzationServiceImpl extends RemoteServiceServlet
implements OAuthoritzationService {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(OAuthoritzationServiceImpl.class.getName());
private static String KEY_PARAM = "oauth_consumer_key";
private static String SECRET_PARAM = "oauth_consumer_secret";
private static String SCOPE_PARAM = "scope_calendars";
private static String CALLBACK_PARAM = "oauth_callback";
public String checkOauthTokenSecret(){
ServletContext context = this.getServletContext();
getOauthParams(context);
return (String) this.getThreadLocalRequest().getSession().getAttribute("oauthTokenSecret");;
}
public String getApprovalOAuthPageURL() throws IOException{
ServletContext context = this.getServletContext();
getOauthParams(context);
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
oauthParameters.setScope(getFromSession(SCOPE_PARAM));
oauthParameters.setOAuthCallback(getFromSession(CALLBACK_PARAM));
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
try {
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();
this.getThreadLocalRequest().getSession().setAttribute("oauthTokenSecret", oauthTokenSecret);
return approvalPageUrl;
} catch (OAuthException e) {
log.log(Level.WARNING,e.toString());
return "";
} finally{
}
}
public LoginInfo upgradeLogin(String queryString, LoginInfo login){
// receiving '?key1=value1&key2=value2
queryString = queryString.substring(1, queryString.length());
String k = getFromSession(KEY_PARAM);
String s = getFromSession(SECRET_PARAM);
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(k);
oauthParameters.setOAuthConsumerSecret(s);
String oauthTS = (String) this.getThreadLocalRequest().getSession().getAttribute("oauthTokenSecret");//oauthParameters.getOAuthTokenSecret();
oauthParameters.setOAuthTokenSecret(oauthTS);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthHelper.getOAuthParametersFromCallback(queryString,oauthParameters);
login.setQueryStringTokens(queryString);
login.setAccessTokenSecret(oauthTS);
try {
String accesToken = oauthHelper.getAccessToken(oauthParameters);
login.setTokenSecret(accesToken);
} catch (OAuthException e) {
log.log(Level.WARNING,e.toString());
}
return login;
}
public ArrayList<String> getPublicCalendars(String accessToken, String accessTokenSecret){
ArrayList<String> result = new ArrayList<String>();
CalendarFeed calendarResultFeed = null;
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
oauthParameters.setOAuthToken(accessToken);
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
oauthParameters.setScope(getFromSession(SCOPE_PARAM));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
try {
myService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL calendarFeedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
calendarResultFeed = myService.getFeed(calendarFeedUrl, CalendarFeed.class);
} catch (OAuthException e) {
log.info("OAuthException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (MalformedURLException e) {
log.info("MalformedURLException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (IOException e) {
log.info("IOException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (ServiceException e) {
log.info("ServiceException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
}
if (calendarResultFeed != null && calendarResultFeed.getEntries() != null) {
for (int i = 0; i < calendarResultFeed.getEntries().size(); i++) {
CalendarEntry entry = calendarResultFeed.getEntries().get(i);
result.add(entry.getTitle().getPlainText());
}
}
return result;
}
private void getOauthParams(ServletContext context) {
this.getThreadLocalRequest().getSession()
.setAttribute(KEY_PARAM, context.getInitParameter(KEY_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(SECRET_PARAM, context.getInitParameter(SECRET_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(SCOPE_PARAM, context.getInitParameter(SCOPE_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(CALLBACK_PARAM, context.getInitParameter(CALLBACK_PARAM));
}
private String getFromSession(String param){
return (String) this.getThreadLocalRequest().getSession().getAttribute(param);
}
}
I have recently been working with oAuth. Inside upgradeLogin(...) when you are upgrading to an access token you are not fetching the respective access token secret.
The access token secret following the getAccessToken() request is different to the access token secret before the request. You are currently setting the access token secret (via login.setAccessTokenSecret(oauthTS)), it is the pre-updated access token secret value you are using. You need to set it to the access token secret value returned after the update request:
String accesToken = oauthHelper.getAccessToken(oauthParameters);
String accesTokenSecret = oauthParameters.getOAuthTokenSecret();
login.setTokenSecret(accesToken);
login.setAccessTokenSecret(accesTokenSecret);
You also probably want to store this updated token/secret pair somewhere. It is this value of access token secret that should then to be used inside getPublicCalendars(...) in the line:
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
The post update access token/secret pair is long-lived and can therefore be re-used (without needing to update it again) until such time as it is revoked.
Incidentally I found the oAuth Playground Tool useful in diagnosing my problems.
I hope this helps,