GWT Facebook Integration - java

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>

Related

How to show browser login form for basic authentication using RESTEasy

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

Verify transaction on Google App Engine

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?

Facing Issue While Integrating Google Login Button With Java Application

I am working on Hybris Technology. It is nothing but the Java only. So I am trying to Integrate Google Login Button with my Java Application.
I am following this tutorial. Here is my code What I am doing
Front Part --
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
(function () {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<div id="signinButton">
<span class="g-signin" data-scope="https://www.googleapis.com/auth/plus.login"
data-clientid="*****************************"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback">
</span>
</div>
<div id="result"></div>
<script type="text/javascript">
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'GET',
url: '/store/en/login/lnregister',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response if necessary.
// Prints the list of people that the user has allowed the app to know
// to the console.
console.log(result);
if (result['profile'] && result['people']){
$('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list');
} else {
$('#results').html('Failed to make a server-side call. Check your configuration and console.');
}
},
processData: false,
data: authResult['code']
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
// console.log('There was an error: ' + authResult['error']);
}
}
</script>
Here I am using ajax to call my controller function lnregister.
#RequestMapping(value = "/lnregister", method = RequestMethod.GET)
public String doLnRegister(#RequestHeader(value = "referer", required = false) final String referer, final RegisterForm form,
final BindingResult bindingResult, final Model model, final HttpServletRequest request,
final HttpServletResponse response, final RedirectAttributes redirectModel) throws CMSItemNotFoundException
{
final Gson gson = new Gson();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
final String APPLICATION_NAME = "HybrisProject";
final HttpTransport TRANSPORT = new HttpTransport()
{
#Override
protected final LowLevelHttpRequest buildRequest(final String arg0, final String arg1) throws IOException
{
// YTODO Auto-generated method stub
return null;
}
};
final String CLIENT_ID = "************************";
final String CLIENT_SECRET = "*******************";
// Create a state token to prevent request forgery.
// Store it in the session for later validation.
final String state = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state);
// Read index.html into memory, and set the Client ID,
// Token State, and Application Name in the HTML before serving it.
try
{
return new Scanner(new File("index.html"), "UTF-8").useDelimiter("\\A").next()
.replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID).replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
.replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME);
}
catch (final FileNotFoundException e2)
{
// YTODO Auto-generated catch block
e2.printStackTrace();
}
if (!request.getParameter("state").equals(request.getSession().getAttribute("state")))
{
response.setStatus(401);
gson.toJson("Invalid state parameter.");
}
final String gPlusId = request.getParameter("gplus_id");
String code = null;
try
{
code = request.getReader().toString();
}
catch (final IOException e1)
{
// YTODO Auto-generated catch block
e1.printStackTrace();
}
try
{
// Upgrade the authorization code into an access and refresh token.
final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID,
CLIENT_SECRET, code, "postmessage").execute();
// Create a credential representation of the token data.
final GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setFromTokenResponse(tokenResponse);
// Check that the token is valid.
final Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build();
final Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
// If there was an error in the token info, abort.
if (tokenInfo.containsKey("error"))
{
response.setStatus(401);
return gson.toJson(tokenInfo.get("error").toString());
}
// Make sure the token we got is for the intended user.
if (!tokenInfo.getUserId().equals(gPlusId))
{
response.setStatus(401);
return gson.toJson("Token's user ID doesn't match given user ID.");
}
// Make sure the token we got is for our app.
if (!tokenInfo.getIssuedTo().equals(CLIENT_ID))
{
response.setStatus(401);
return gson.toJson("Token's client ID does not match app's.");
}
// Store the token in the session for later use.
request.getSession().setAttribute("token", tokenResponse.toString());
return gson.toJson("Successfully connected user.");
}
catch (final TokenResponseException e)
{
response.setStatus(500);
return gson.toJson("Failed to upgrade the authorization code.");
}
catch (final IOException e)
{
response.setStatus(500);
return gson.toJson("Failed to read token data from Google. " + e.getMessage());
}
}
Here my Question is Am I going in right direction. Is it a proper way to connect java application with Google Login API. My Front View is working fine. When I click on google+ button, request also going to my controller. But There in backend side I am getting error. I am not pasting this error bacause error like NullPointerException or like that.
My Question is I am going in a proper way or not. If It is not, then what is the right way. Please help me.
You are making this very hard for yourself, and re-implementing too much.
Read http://krams915.blogspot.se/2011/02/spring-security-3-openid-login-with_13.html
You just need to ensure your Provider and UserDetailsService do what you need.

Web app and request authentication

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

HtmlUnit's WebClient fails on second identical loadWebResponse() call

I'm attempting to write tests for a very long and kludgy "getPost" method in a webapp I'm working on for my job. I'm using JUnit, HtmlUnit, and Jetty's ServletTester to approximate sending a request to a servlet and receiving a response. I've managed to get it mostly working, but I'm having a problem. I'm trying to test the login functionality. If the user logs in successfully, the server should send some JSON back to the client with the user's information. If the user is already logged in, the server should send back "result": "failure" and an error message.
My problem comes when I try to test the second requirement. I can log in successfully, and get the correct data back. However, when I try to send the request again, it returns 404: not found. I tried breaking the code up into different tests, but I have to be able to call login twice in order to test the second requirement. Later tests in the JUnit file run just fine, and the servlet is staying connected the same time. I tried making a second, identical request, but that also failed. I've searched the internet to no avail. In short, I'm stumped.
Here's what I'm working with (unnecessary code has been edited out):
//In MyFunServlet class:
private final static String USERID_ATTRIBUTENAME = "userid";
void doPost(HttpServletRequest request, HttpServletResponse response) {
String action = request.getParameter("opt");
final HttpSession session = request.getSession();
if(action != null){
Long userId = (Long)session.getAttribute(USERID_ATTRIBUTENAME);
if(userId != null){
//do stuffz
} else {
if(action.equals("login")) {
User user = LoginUser(request, response);
try{
JSONObject json = new JSONObject();
if(request.getAttribute("result") == "success"){
json.put("result", "success");
json.put("id", user.getId());
json.put("name", user.getName());
} else {
json.put("result", "failure");
json.put("message", request.getAttribute("message"));
}
SendJSONResponse(json, request, response);
}catch(Exception e){
}
} else {
System.out.print("Unknown opt: " + action);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
}
}
private void LoginUser(HttpServletRequest request, HttpServletResponse response){
final HttpSession session = request.getSession();
User user = null;
Long userId = (Long)session.getAttribute(USERID_ATTRIBUTENAME);
if(userId != null){
request.setAttribute("result", "failure");
request.setAttribute("message", "The user is already logged in.");
} else {
final String email = request.getParameter("accountEmail");
final String password = request.getParameter("accountPassword");
if(email != null) {
user = helperClass.magicallyGetUserByEmail(email);
if(user != null){
if(user.getPassword().equals(password)){
session.setAttribute(USERID_ATTRIBUTENAME, user.getId();
request.setAttribute("result", "success");
}
}
} else {
request.setAttribute("result", "failure");
}
}
return user;
}
private void SendJSONResponse(JSONObject json, HttpServletRequest request,
HttpServletResponse response) {
String contentStr = json.toString();
response.setContentType("application/json");
response.setStatus( HttpServletResponse.SC_OK);
response.setContentLength(contentStr.length());
response.getWriter().print(contentStr);
response.flushBuffer();
}
For reference purposes, this file is 1084 lines long. The doPost method is about 900 of those. Disclaimer: this is not my code. I did not write it. I only have to test it.
Now for the test:
//In MyFunServletTest.java:
//using JUnit 4
public class MyFunServletTest {
static ServletTester tester;
static String baseUrl;
WebClient webClient = new WebClient();
User user;
WebRequest loginRequest;
#BeforeClass
public static void initClass(){
tester = new ServletTester;
tester.setContextPath("/");
tester.addServlet(MyFunServlet.class, "/fun.service");
baseUrl = tester.createSocketConnector(true);
tester.start();
}
#AfterClass
public static void cleanClass() {
tester.stop();
}
#Before
public void preTest(){
//taking values from our magical test user
user = new User();
user.setEmail("blah#blah.com");
user.setPassword("secure");
loginRequest = new WebRequest(baseUrl + "/fun.service", HttpMethod.POST);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("opt","login"));
params.add(new NameValuePair("accountEmail", user.getEmail());
params.add(new NameValuePair("accountPassword", user.getPassword());
loginRequest.setRequestParameters(params);
}
#Test
public void testLogin() {
WebResponse response = webClient.loadWebResponse(loginRequest);
JSONObject responseJSON = new JSONObject(response.getContentAsString());
//this test passes
assertEquals("success", responseJSON.getString("result"));
response = webClient.loadWebResponse(loginRequest);
//this test fails
assertTrue(404 != response.getStatusCode());
//this then causes an error, as response.getContentAsString() is null.
esponseJSON = new JSONObject(response.getContentAsString());
}
}
Help? Where am I missing something?
Thanks.
Without the ability to run the test myself, I can only offer some approaches:
Try creating two JSONObject objects to store the two responses separately, and compare the two (either print them or using the debugger), see if anything looks odd there.
If that doesn't tell you anything, create two separate identical request instances and use each.
Then try tracing through the call to loadWebResponse to see exactly what URL is being requested (cranking up the log level might tell you this, too).
If the 404 is correct, then the second request is somehow being mangled, but the question would be WHERE.

Categories