I'm trying to get the transaction verification working for making an in-app purchase on Android in countries where Google Play isn't available.
When using the sandbox API everything seems to work well on my local Google App Engine dev server. The server sends a request to PayPal with the transaction ID and comes back with the JSON response containing the state of the transaction.
When I upload the code to Google App Engine, however, it instead uses the live API with corresponding credentials. When I do the transaction verification there, I get the following error from the Paypal REST SDK:
Response Code : 401 with response : {"error":"invalid_client","error_description":"The client credentials are invalid"}
In the HttpServlet I use this to set the constant DEBUG to true or false:
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
String dev = config.getServletContext().getServerInfo();
if (dev.contains("Development")) {
Constants.DEBUG = true;
} else {
Constants.DEBUG = false;
}
}
The transaction ID is verified with the code below. It gets the access token for making the API call and then verifies the transaction id. I also create a custom config which sets GOOGLE_APP_ENGINE to true and MODE to sandbox or live depending on the DEBUG constant (this is because I couldn't get the getServletContext().getResourceAsStream("sdk_config.properties") working as it gave an Access denied error).
public static String getAccessToken() throws PayPalRESTException {
String clientSecret, clientID;
if (Constants.DEBUG) {
clientSecret = Constants.CLIENT_SECRET_SANDBOX;
clientID = Constants.CLIENT_ID_SANDBOX;
} else {
clientSecret = Constants.CLIENT_SECRET_LIVE;
clientID = Constants.CLIENT_ID_LIVE;
}
return new OAuthTokenCredential(clientID, clientSecret,
getPaypalConfig()).getAccessToken();
}
public static Map<String, String> getPaypalConfig() {
Map<String, String> config = new HashMap<>();
config.put(com.paypal.core.Constants.GOOGLE_APP_ENGINE,
String.valueOf(true));
if (Constants.DEBUG) {
config.put(com.paypal.core.Constants.MODE,
com.paypal.core.Constants.SANDBOX);
} else {
config.put(com.paypal.core.Constants.MODE,
com.paypal.core.Constants.LIVE);
}
return config;
}
public static boolean payPalVerifier(String saleId)
throws PayPalRESTException {
if (accessToken == null) {
accessToken = Utils.getAccessToken();
apiContext = new APIContext(accessToken);
apiContext.setConfigurationMap(Utils.getPaypalConfig());
}
boolean completed = false;
Payment pay = Payment.get(apiContext, saleId);
for (Transaction transaction : pay.getTransactions()) {
for (RelatedResources relatedResources : transaction
.getRelatedResources()) {
if (com.pixplicity.Constants.DEBUG) {
completed = relatedResources.getSale().getState()
.equals("completed")
|| relatedResources.getSale().getState()
.equals("pending");
} else {
completed = relatedResources.getSale().getState()
.equals("completed");
}
}
}
return completed;
}
How do I solve this problem?
Related
I´m currently messing around with JAX-RS specifically Resteasy, because it "just works" with Wildfly and I don´t have to configure anything. That´s really the only reason I use that.
I did already implement Basic Authentication, looking forward to replacing it with OAuth2 later, just did this now for simplicity reasons.
The ContainerRequestFilter looks like this
#Provider
public class SecurityFilter implements ContainerRequestFilter {
private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
private static final String AUTHORIZATION_HEADER_PREFIX = "Basic ";
#Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
if(isAuthenticated(containerRequestContext) == false)
containerRequestContext.abortWith(createUnauthorizedResponse("Access denied."));
}
private boolean isAuthenticated(ContainerRequestContext containerRequestContext) {
List<String> authHeader = containerRequestContext.getHeaders().get(AUTHORIZATION_HEADER_KEY);
ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) containerRequestContext.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
Method method = methodInvoker.getMethod();
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
if (authHeader != null && authHeader.size() > 0) {
String authToken = authHeader.get(0).replaceFirst(AUTHORIZATION_HEADER_PREFIX, "");
byte[] decoded = null;
try {
decoded = Base64.getDecoder().decode(authToken);
} catch (IllegalArgumentException ex) {
return false;
}
String decodedString = new String(decoded);
StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
String username = null, password = null;
if(tokenizer.countTokens() < 2)
return false;
username = tokenizer.nextToken();
password = tokenizer.nextToken();
if (DbController.isValid(username, password, rolesAnnotation.value()))
return true;
}
return false;
}
private Response createUnauthorizedResponse(String msg) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity("{ \"Unauthorized\" : \"" + msg + "\" }")
.type(MediaType.APPLICATION_JSON)
.build();
}
}
It works fine with postman. And I do realize that the main usage of such apis is in well other programs.
But it would be nice, if opened in a browser it would ask you to enter your credentials, instead of just telling you that you are not authorized, with no way to really enter your credentials. Unless you do some trickery to manually put it in the header, but then you might as well just use postman.
If I put a security constraint with auth-constraint role admin it does give a login dialog, but then the authorization does not work and it just keeps asking for authorization.
Is there anything else that I can do instead of containerRequestContext.abortWith? Or do I need to use a completely different approach and it just won´t work with ContainerRequestFilter?
You need to add the WWW-Authenticate header to the response that you abort with. This header tells the browser that it should present the default browser login form.
private static final String CHALLENGE_FORMAT = "%s realm=\"%s\"";
private Response createUnauthorizedResponse() {
return Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE, String.format(CHALLENGE_FORMAT, "Basic", "Access"))
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("Credentials are required to access this resource.")
.build();
And here's what the login should look like on Chrome
So I have an app which uses Google App Engine and Google Cloud Endpoints as it's backend in Java. I'm currently working on User authentication and here is what I'm trying to do:
When user first opens the app, they'll have option to either "Login through Facebook" or signup using their email address. Then this data would be stored in a user object and after registration would direct them to the app homepage. It will be saved in their preferences so that they don't need to login every time they open the app (if ever).
Now I heard you can use a custom authenticator for Facebook, but there's not much documentation regarding this. How can I get the email registration and Facebook Login options to be implemented with Google Cloud Endpoint's Authenticator? Or should I make a different approach?
Thanks.
My approach is using the Facebook login method (Facebook SDK for Android). The Facebook authentication process returns (on success) an object from which I can get the user's email then I save it in my Endpoints class using Datastore API. To check if user already logged in I chose the SharedPreferences approach with GSON library to parse objects into JSON String and save them in the prefs.
Links and my sample codes below :
Regarding the Authenticator I found this SO answer
More info about Facebook login method
Saving custom objects in SharedPreferences
Getting user's email through Facebook auth
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
if (isSessionCalled == false) {
Log.i(TAG, "Logged in...");
System.out.println("Token=" + session.getAccessToken());
new Request(
session,
"/me",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
if (response != null) {
GraphObject object = response.getGraphObject();
String email = (String) object.getProperty("email");
Log.i(TAG, "user email : " + email);
String firstName = (String) object.getProperty("first_name");
String lastName = (String) object.getProperty("last_name");
mUserTask = new UserAsyncTask();
mUserTask.execute(email);
}
}
}
).executeAsync();
isSessionCalled = true;
}
else {
Log.w(TAG, "session called twice");
}
}
else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
Storing the user in my backend :
#ApiMethod(name = "storeUserModel")
public UserModel storeUserModel(UserModel userModel) throws UserAlreadyExistsException, UserNotFoundException {
logger.info("inside storeUser");
String email = userModel.getEmail();
UserModel checkUser = getUserModel(email);
logger.info("after getUserModel with email " + email);
if (checkUser == null) {
logger.info("inside checkUser is NULL");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction txn = datastoreService.beginTransaction();
try {
Entity userEntity = new Entity(UserModel.class.getSimpleName(), email);
userEntity.setProperty("nickname", userModel.getNickname());
// TODO save the pheromones with the key of userEntity
datastoreService.put(userEntity);
txn.commit();
storePheromoneList(userModel.getPheromoneList(), userEntity.getKey(), datastoreService);
} finally {
if (txn.isActive()) {
logger.severe("rolled back with email : " + email);
txn.rollback();
}
}
}
else {
throw new UserAlreadyExistsException();
}
return userModel;
}
A class that triggers calls to my backend
public class EndpointsServer implements Server {
private static final String TAG = "EndpointsServer";
final UserModelApi userEndpointsApi;
public EndpointsServer() {
UserModelApi.Builder builder = new UserModelApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
userEndpointsApi = builder.build();
}
#Override
public User getUser(String email) {
User user = null;
try {
Log.d(TAG, "in getUser with email " +email);
// get user from db
UserModel userModel = userEndpointsApi.getUserModel(email).execute();
if (userModel != null) {
Log.d(TAG, "user != null with email " + email);
user = new User(userModel);
}
} catch (IOException e) {
e.printStackTrace();
}
return user;
}
}
Storing user on successful login :
String userString = gson.toJson(user, User.class);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(USER_KEY, userString);
editor.commit();
There's more to it like another client side class to build the api call to the backend and lots of other details. I can post it if you want.
I can't speak on Java but I started with Python by looking at this repo on Github:
https://github.com/loudnate/appengine-endpoints-auth-example
This shows you an example on how to write a custom authenticator with Facebook Login. Writing your own authentication I think you should be able to find some examples. The only thing you need to do after is to use the same User entity.
And I suggest you do some reading on how OAUTH 2.0 works so you don't get too confused on the task you need to do.
Basically:
On your client side, whether web or android, get a facebook access token, sends it to your endpoint service. Exchange for a access token of your own. At the same time, create your User object in datastore and associate the access token.
Then all your subsequent request should use this access token to get access to your endpoint backend. (Do a user check on your endpoint API method.)
I currently have a working web app, but I need to provide means for friend website to consume my data.
There is currently JSON response in place which retrieves some data from my website to caller. It's without authentication currently and I'd like to implement some kind of per request authentication.
My web app has users which are logged in and there is a authentication in place for that. But
I have 3 requests in total for which callers can get data off of my website, what would be the simplest way to add some kind of authentication just for those 3 requests?
I'm using play framework + java
Imo the best options for this would be in the order of simplicity:
Basic authentication (since it's possible to choose either to auth once and then do session-base user recognition or authorize on every request)
2-way SSL
Combination of both
What toolkit do you use for authentication part?
I personally stuck with play-authenticate. So I might be able to answer you question in regard to this toolkit, please apply it to your particular toolkit as needed.
I will provide Basic authentication example as the easiest one. The benefit is: you could start with it and add on top it later (e.g. add Client certificate authentication via Apache later on).
So, my controller code snippet
#Restrict(value = #Group({"ROLE_WEB_SERVICE1"}), handler = BasicAuthHandler.class)
public static Result ws1() {
return TODO;
}
And the authentification handler itself
public class BasicAuthHandler extends AbstractDeadboltHandler {
public static final String HEADER_PREFIX = "Basic ";
private static final String AUTHORIZATION = "authorization";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
#Override
public Result beforeAuthCheck(final Http.Context context) {
return basicAuthenticate(context);
}
private Result basicAuthenticate(Http.Context context) {
if (PlayAuthenticate.isLoggedIn(context.session())) {
// user is logged in
return null;
}
final String authHeader = context.request().getHeader(AUTHORIZATION);
if (authHeader == null || !authHeader.toLowerCase().startsWith(HEADER_PREFIX.toLowerCase())) {
return onAuthFailure(context, "Basic authentication header is missing");
}
final String auth = authHeader.substring(HEADER_PREFIX.length());
final byte[] decodedAuth;
final String[] credentials;
try {
decodedAuth = Base64.base64ToByteArray(auth);
credentials = new String(decodedAuth, "UTF-8").split(":");
} catch (final IOException e) {
Logger.error("basicAuthenticate", e);
return Results.internalServerError();
}
if (credentials.length != 2) {
return onAuthFailure(context, "Could not authenticate with absent password");
}
final String username = credentials[0];
final String password = credentials[1];
final AuthUser authUser = new AuthUser(password, username);
final Enum result = AuthProvider.getProvider().loginUser(authUser);
if ("USER_LOGGED_IN".equals(result.name())) {
PlayAuthenticate.storeUser(context.session(), authUser);
return null;
}
return onAuthFailure(context, "Authenticate failure");
}
#Override
public Subject getSubject(final Http.Context context) {
// your implementation
}
#Override
public Result onAuthFailure(final Http.Context context,
final String content) {
// your error hangling logic
return super.onAuthFailure(context, content);
}
}
Hopefully it fills in some blanks
I am trying to access Adsense Management API using java google-api. However, I having troubles with oauth2 authentication. According with the doc the following code should be enough:
public static GoogleCredential getCredential()
throws GeneralSecurityException, IOException {
File file = new File("key.p12");
return new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_ID)
.setServiceAccountScopes(AdSenseScopes.ADSENSE)
.setServiceAccountPrivateKeyFromP12File(file)
.setServiceAccountUser(ACCOUNT_USER)
.build();
}
However, credential always returning accessToken null and I can't do any operation. I am getting a bad request:
Exception in thread "main" java.lang.RuntimeException: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
My client code:
private static AdSense initializeAdsense() throws Exception {
// Authorization.
Credential credential = getCredential();
String token = credential.getAccessToken();
System.out.println(token);
AdSense adsense = new AdSense.Builder(new NetHttpTransport(), JSON_FACTORY, credential).setApplicationName("Google-AdSenseSample/1.2").build();
return adsense;
}
public static Accounts run(AdSense adsense, int maxPageSize) throws Exception {
System.out.println("=================================================================");
System.out.println("Listing all AdSense accounts");
System.out.println("=================================================================");
// Retrieve account list in pages and display data as we receive it.
String pageToken = null;
Accounts accounts = null;
do {
accounts = adsense.accounts().list().setMaxResults(maxPageSize).setPageToken(pageToken).execute();
if ((accounts.getItems() != null) && !accounts.getItems().isEmpty()) {
for (Account account : accounts.getItems()) {
System.out.printf("Account with ID \"%s\" and name \"%s\" was found.\n", account.getId(), account.getName());
}
} else {
System.out.println("No accounts found.");
}
pageToken = accounts.getNextPageToken();
} while (pageToken != null);
System.out.println();
return accounts;
}
public static void test() throws Exception {
AdSense adsense = initializeAdsense();
run(adsense, 30);
}
The question is, after all, what is wrong?
Edited:
Maybe I just cannot do that.
I'm afraid that accessing the AdSense Management API via service account authentication is not supported, since it's protected user information
https://groups.google.com/forum/#!msg/adsense-api/j-gQsp_fE94/CrOPhRLv4WUJ
SERVICE_ACCOUNT_ID should be email address of your service account (xxxxxx#developer.gserviceaccount.com) and do not set the ACCOUNT_USER.
I am trying to write a server side Facebook Notification service in my GWT app. The idea is that I will run this as a timertask or cron job sort of.
With the code below, I get a login URL, I want to be able to Login programmatically as this is intended to be automated (Headless sort of way). I was gonna try do a submit with HTMLunit but I thought the FB API should cater for this.
Please advice.
public class NotificationServiceImpl extends RemoteServiceServlet implements NotificationService {
/**serialVersionUID*/
private static final long serialVersionUID = 6893572879522128833L;
private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
long facebookUserID;
public String sendMessage(Notification notification) throws IOException {
String api_key = notification.getApi_key();
String secret = notification.getSecret_key();
try {
// MDC.put(ipAddress, req.getRemoteAddr());
HttpServletRequest request = getThreadLocalRequest();
HttpServletResponse response = getThreadLocalResponse();
HttpSession session = getThreadLocalRequest().getSession(true);
// session.setAttribute("api_key", api_key);
IFacebookRestClient<Document> userClient = getUserClient(session);
if(userClient == null) {
System.out.println("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
userClient = new FacebookXmlRestClient(api_key, secret);
session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
}
System.out.println("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(request, response, api_key, secret, userClient);
String nextPage = request.getRequestURI();
nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); //cut out the first /, the context path and the 2nd /
System.out.println(nextPage);
boolean redirectOccurred = facebook.requireLogin(nextPage);
if(redirectOccurred) {
return null;
}
redirectOccurred = facebook.requireFrame(nextPage);
if(redirectOccurred) {
return null;
}
try {
facebookUserID = userClient.users_getLoggedInUser();
if (userClient.users_hasAppPermission(Permission.STATUS_UPDATE)) {
userClient.users_setStatus("Im testing Facebook With Java! This status is written using my Java code! Can you see it? Cool :D", false);
}
} catch(FacebookException ex) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while fetching user's facebook ID");
System.out.println("Error while getting cached (supplied by request params) value " +
"of the user's facebook ID or while fetching it from the Facebook service " +
"if the cached value was not present for some reason. Cached value = {}" + userClient.getCacheUserId());
return null;
}
// MDC.put(facebookUserId, String.valueOf(facebookUserID));
// chain.doFilter(request, response);
} finally {
// MDC.remove(ipAddress);
// MDC.remove(facebookUserId);
}
return String.valueOf(facebookUserID);
}
public static FacebookXmlRestClient getUserClient(HttpSession session) {
return (FacebookXmlRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
}
}
Error message:
[ERROR] com.google.gwt.user.client.rpc.InvocationException: <script type="text/javascript">
[ERROR] top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key=MY_KEY&next=notification";
[ERROR] </script>