facebook sharing on servlet, jsp; getting auth code; - facebook

public FacebookConnector() {
try {
FacebookClient.AccessToken token = getFacebookUserToken("???", "http://localhost:8083/CrunchifyJSPServletExample/");
String accessToken = token.getAccessToken();
Date expires = token.getExpires();
fbClient = new DefaultFacebookClient(this.accessToken, Version.LATEST);
myuser = fbClient.fetchObject("me", User.class);
mypage = fbClient.fetchObject(pageID, Page.class);
counter = 0;
} catch (Exception ex) { //So that you can see what went wrong
ex.printStackTrace(System.err); //in case you did anything incorrectly
}
}
public void makeTestPost() {
FacebookType publishMessageResponse = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", "Test from Graph API"));
System.out.println("Published message ID: " + publishMessageResponse.getId());
}
private FacebookClient.AccessToken getFacebookUserToken(String code, String redirectUrl) throws IOException {
String appId = "My App Id";
String secretKey = "My Secret Key";
WebRequestor wr = new DefaultWebRequestor();
WebRequestor.Response accessTokenResponse = wr.executeGet(
"https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirectUrl
+ "&client_secret=" + secretKey + "&code=" + code);
return DefaultFacebookClient.AccessToken.fromQueryString(accessTokenResponse.getBody());
}
I am working on enabling facebook sharing for my application that is built on JSP and servlet.
I am using above code.
I need your inputs on 2 things:
1) If my approach is correct.
2) How to get auth code? So that can help me in getting authentication token.
Help of any sort is appreciated. Thanks. AY

For facebook authentication you can do like that:-
Click
It will generate code then use this code to send request to graph.facebook as you written correctly in your code then it will generate accesscode and use accesscode as per your requirement

Related

QSH Verification, I have tried to verify qsh string but i get a "abc" qsh instead of the "def" qsh from the JWT token

I have used this video to properly understand how JWT QSH is created from a SHA hashed conical request
https://www.youtube.com/watch?v=5EpEMKPbUjU
I also have gone through, this site Understanding JWT. https://developer.atlassian.com/cloud/jira/platform/understanding-jwt-for-connect-apps/.
I have replicated everything done there, and still confused. I have never been able to reproduce the qsh.
if (verifiedClaims.qsh) {
const { baseUrl } = payload;
const url = JWTHelper.decodeUrlToMatchJWTQueryStringHash(baseUrl);
logger.debug(`url[${url}]`);
const req = jwt.fromMethodAndUrl("GET", url);
logger.debug(`req[${JSON.stringify(req)}]`);
let expectedHash = jwt.createQueryStringHash(req);
logger.debug(`expectedHash[${expectedHash}]`);
let signatureHashVerified = verifiedClaims.qsh === expectedHash;
logger.json("signatureHashVerified", { qsh: verifiedClaims.qsh, expectedHash, signatureHashVerified });
if (!signatureHashVerified) {
// If signatureVerified is false, then check the url if its a PUT/POST
expectedHash = jwt.createQueryStringHash(req, url);
signatureHashVerified = verifiedClaims.qsh === expectedHash;
logger.json("signatureHashVerified", { qsh: verifiedClaims.qsh, expectedHash, signatureHashVerified });
if (verifiedClaims.qsh !== expectedHash && verifiedClaims.qsh !== "context-qsh") {
const canonicalRequest = jwt.createCanonicalRequest(req, true, url);
logger.error(
'Auth failure: Query hash mismatch: Received: "' + verifiedClaims.qsh + '" but calculated "' + expectedHash + '". ' +
'Canonical query was: "' + canonicalRequest);
throw new Error("Authentication failed: query hash does not match.");
}
}
}
The code above is from the Link, understanding jwt. I am using atlassian-jwt npm package
https://www.npmjs.com/package/atlassian-jwt.
Please where am I getting it all wrong, from my codes or from any perspective what can I do to fix the issue and verify qsh

Cannot POST to OneNote Client

I cannot avoid getting the following error :
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
Here is my code:
public async Task<string> SendPostRequest(string _AccessToken)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + _AccessToken);
string date = GetDate();
string simpleHtml = "<html>" +
"<head>" +
"<title>A simple page created from basic HTML-formatted text</title>" +
"<meta name=\"created\" content=\"" + date + "\" />" +
"</head>" +
"<body>" +
"<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>" +
"<p>Here is a link</p>" +
"</body>" +
"</html>";
var createMessage = new HttpRequestMessage(HttpMethod.Post, _GraphAPIEndpoint)
{
Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
};
HttpResponseMessage response = await httpClient.SendAsync(createMessage);
return response.ToString();
}
Here is the GraphEndpoint:
private string _GraphAPIEndpoint ="https://www.onenote.com/api/v1.0/pages";
Everything looks good with the login and authentication. I get a token etc.
Here is the code for getting my token:
private const string _ClientID = "981c0157-69ec-4f42-8ec6-xxxxxxxxxxxxx";
public static PublicClientApplication clientApplication = new PublicClientApplication(_ClientID);
private AuthenticationResult authResult = null;
authResult = await App.clientApplication.AcquireTokenAsync(_Scopes);
if (authResult != null)
{
string response = await SendPostRequest(authResult.AccessToken);
}
The following combination finally works:
private string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/onenote/pages";
private string[] scopes = new string[] { "Notes.ReadWrite" };
It would have been easier if some of the github OneNote Samples would have been updated.
How are you obtaining your token?
If you're obtaining your token through login.microsoftonline.com, then try posting to
https://graph.microsoft.com/v1.0/me/onenote/pages
It seems you're using C# - I'd recommend looking at the samples we have, and using them as a reference.
https://github.com/OneNoteDev/MsGraph_OneNoteApiSampleAspNetCore
https://github.com/OneNoteDev/OneNoteAPISampleWinUniversal
The Live SDK is deprecated - you shouldn't use it. I recommend the following for you then: developer.microsoft.com/en-us/graph/code-samples-and-sdks Microsoft Graph SDKs and samples span many platforms and use latest, supported authentication frameworks. With those, you can call POST ~/pages (there's even SDK support)
The endpoint does not look correct. It should be either be as provided by Jorge above or if you are hitting OneNote API directly, it should be: "https://www.onenote.com/api/v1.0/me/notes/pages"

How to redirect in JAX-RS after a post to a get

I'm developing a simple login form (security is not a problem) where the user visits the page login inserts username and password and press send that POST these information to the page check.
Page check checks credential and, if everything is OK, creates cookie and redirect to page home, otherwise redirects to page login.
I use the following redirect:
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
This redirects from check (#POST method) to home (#POST method), I just wanna to redirect to home (#GET method).
Important note: I'm a newbie of JAX and what I would like to create is a RESTful service. Are redirects a correct way to implement a REST service?
Now I'll show you small slices of code hoping:
check Page
#POST
#Produces(MediaType.TEXT_HTML)
public Response checkLogin(#FormParam(Login.fieldUsername) String user, #FormParam(Login.fieldPsw) String psw) throws URISyntaxException {
boolean val = db.checkLogin(user, psw);
NewCookie cookie;
NewCookie cookie2;
if(val){
//Valid access + cookie creation
cookie = new NewCookie("username", user);
cookie2 = new NewCookie("hashedPassword", psw);
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
} else {
//Wrong login + cookie deletion
cookie = new NewCookie("username", "");
cookie2 = new NewCookie("hashedPassword", "");
return Response.temporaryRedirect(new URI("/login")).cookie(cookie, cookie2).build();
}
}
login page
#GET
#Produces(MediaType.TEXT_HTML)
public Response showLoginForm() throws URISyntaxException{
boolean validCookie = db.checkLogin(username, hashedPassword);
String data = "<form name='Username' action='"+ redirect +"' method='post'><ul>"
+ "<li><label for='"+fieldUsername+"'>Username</label>"
+ " <input type='text' name='"+fieldUsername+"' placeholder='Insert username' required></li>"
+ "<li><label for='"+fieldPsw+"'>Password</label>"
+ " <input type='password' name='"+fieldPsw+"' placeholder='Insert password' required></li>"
+ "<li><input type='submit' value='Login'>"
+ "</li></ul></form>";
if(validCookie){
return Response.temporaryRedirect(new URI(homepage)).build();
}
else {
return Response.ok( showTheForm(data) ).build();
}
}
You can use:
Response.seeOther(redirecttUri).build();

Issue using Insights Edge API

I am trying to get some insights data using Insights Edge API, but running into permissions issue:
Here is the code I am using:
string applicationId = "";
string applicationSecret = "";
string accountId = "";
System.Net.WebClient client = new System.Net.WebClient();
string accessToken = client.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + applicationId + "&client_secret=" + applicationSecret + "&grant_type=client_credentials").Replace("access_token=","");
System.Net.WebRequest req = System.Net.WebRequest.Create("https://graph.facebook.com/v2.4/act_"+accountId+"/insights?access_token=" + accessToken);
System.Net.WebResponse response = req.GetResponse();
using(System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string s = sr.ReadToEnd();
Console.WriteLine(s);
}
I am getting the following JSON back:
{
"error": {
"message": "(#10) You do not have sufficient permissions to perform this action",
"type": "OAuthException",
"code": 10
}
}
Application in question was created under the same Facebook account as the ad account. What do I need to check in account/application settings to see if I have all the correct permissions to access Ad Insights API? The code will need to run in the service that doesn't require user intervention, is application access token the right way to access ad insight data in this case?

Post to Facebook Page from Facebook App

I want to post from my Facebook app to one of my pages using app_id and app_secret. It will help me to post directly without log in to Facebook.
I'm able to post on my profile, but not on my page!
Here is my code:
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type={2}",
app_id, app_secret, "client_credentials");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/my-page-FB-ID/feed", new { desctiption = description, picture = picture, link = link, caption = caption, type = type });