unknown host exception while accessing graph.facebook.com - facebook-graph-api

I'm getting an java.net.unknownhostexception while accessing the URL but i'm able to access through browser.
public static void main(String[] args) throws IOException, JSONException`enter code here`
{
JSONObject json = readJsonFromUrl("https://graph.facebook.com/page_id/?
access_token=xxxxx&fields=name,likes,posts");
System.out.println(json.toString());
System.out.println(json.get("likes"));
}

The request URL you're using is not valid. In your request URL, change page_id to the actual Facebook page id you are trying to request data for, and include the API version you are working with.
E.g. if I wanted to access a page with the id 3454546 -
https://graph.facebook.com/v2.9/3454546?access_token=xxxxx&fields=name,likes,posts

Related

Get Non Expiry S3 URL to store it to dynamodb flutter

Guys, I am working on an application that requires to upload an image to s3 and keep the URL in the dynamodb database, however after the upload the geturl function which I have generates the URL for a certain time which has an expiry, how do I get a URL with no expiry
Future<String> getUrl() async {
try {
print('In getUrl');
String key = _uploadFileResult;
try {
GetUrlResult result = await Amplify.Storage.getUrl(key: key);
print(result.url);
return result.url;
} on StorageException catch (e) {
print(e.message);
}
} catch (e) {
print('GetUrl Err: ' + e.toString());
}
}
All S3 pre-signed URLs have an expiration time. Pre-signed URLs exist to share private S3 objects for a limited time.
If that's a problem for you then one option is to make the object public, if appropriate, and simply store its URL of the form https://mybucket.s3.amazonaws.com/images/cat.png.
Alternatively, write a small application that responds to a specific URL (e.g. https://myapi.mydomain.com/images/cat.png and have that app create a pre-signed URL for the related object and issue a 302 redirect to send the client to the temporary, pre-signed URL.

Establish SSO/set cookies with access or id token/token exchange

I'm allowing users logged in an external application to jump into our application with their access token through Keycloak's identity brokering and external to internal token exchange.
Now I'd like to establish an SSO session in an embedded JxBrowser in our application similar to a regular browser login flow, where three cookies are set in the browser: AUTH_SESSION, KEYCLOAK_SESSION(_LEGACY) and KEYCLOAK_IDENTITY(_LEGACY).
KEYCLOAK_IDENTITY contains a token of type Serialized-ID which looks somewhat similar to an ID token.
Is it possible to create the KEYCLOAK_IDENTITY cookie using the exchanged (internal) access and/or ID token and, provided that the other two cookies are correctly created as well, would this establish a valid SSO session?
Basically all I am missing is how I could obtain or create the Serialized-ID type token.
One way to achieve this:
Implement a custom endpoint following this example
Note that the provider works fine for me without registering it in standalone.xml, I'm just adding the JAR to the Keycloak Docker image.
Add a method that validates a given access token, looks up the user, gets the user session and sets the cookies in the response (most error handling omitted for brevity):
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("sso")
public Response sso(#Context final HttpRequest request) {
final HttpHeaders headers = request.getHttpHeaders();
final String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
final String[] value = authorization.split(" ");
final String accessToken = value[1];
final AccessToken token = Tokens.getAccessToken(accessToken, keycloakSession);
if (token == null) {
throw new ErrorResponseException(Errors.INVALID_TOKEN, "Invalid access token", Status.UNAUTHORIZED);
}
final RealmModel realm = keycloakSession.getContext().getRealm();
final UriInfo uriInfo = keycloakSession.getContext().getUri();
final ClientConnection clientConnection = keycloakSession.getContext().getConnection();
final UserModel user = keycloakSession.users().getUserById(token.getSubject(), realm);
final UserSessionModel userSession = keycloakSession.sessions().getUserSession(realm, token.getSessionState());
AuthenticationManager.createLoginCookie(keycloakSession, realm, user, userSession, uriInfo, clientConnection);
return Response.noContent().build();
}
Disclaimer: I am not completely certain this implementation does not imply any security issues, but since Tokens.getAccessToken(accessToken, keycloakSession) does full validation of the access token, setting the cookies should only be possible with a valid access token.
For CORS, add:
#OPTIONS
#Produces(MediaType.APPLICATION_JSON)
#Path("sso")
public Response preflight(#Context final HttpRequest request) {
return Cors.add(request, Response.ok("", MediaType.APPLICATION_JSON))
.auth()
.preflight()
.allowedMethods("GET", "OPTIONS")
.build();
}
and in sso():
return Cors.add(request, Response.ok("", MediaType.APPLICATION_JSON))
.auth()
.allowedMethods("GET")
.allowedOrigins(token)
.build();
What I am uncertain about is why Firefox preflights the GET request, making it necessary to handle that.

How to verify if Redirect from API is working

I have an API method that needs to redirect to URL based on some input provided.
[ApiController]
public class AuthController : ControllerBase
{
[HttpGet()]
public IActionResult GetUrl(string input)
{
// retrieve a url based on the input
string url = GetUrl(input);
return Redirect(url);
}
}
When I debug this method using postman, I see that the correct URL is retrieved and the call to Redirect is made. However, in the postman, I am getting an HTTP 404 status. My questions:
How can I get some appropriate Redirect HTTP status code?
From postman, is there any way to verify if the redirect to URL was performed?
So, I'm thinking your URL that you're passing does not include http:// or https:// in front of it, and ASP.NET is trying to redirect you to http://example.com/url instead of redirecting to an external site. Try adding https:// or http:// in front of your URL that you pass to your GetUrl method. You should then get a 200 OK in Postman.
Example:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
[HttpGet]
public IActionResult GetUrl([FromQuery]string url)
{
return Redirect("https://" + url);
}
}
}
In this example, if you pass url=google.com to the application, you'll get redirected to https://google.com/ and get a 200 OK in Postman.

Jersey filter giving server error

I am using jersey filter.
In My code logic in AuthenticationFilter.java, if the authorization header is empty, then return the access denied error message.
First time I am hitting the application through rest client tool using the URL without attaching the header
http://localhost:8080/JerseyDemos2/rest/pocservice
Get the status 401 with error message "you cannot access this resource". This is right.
When i tried to hit second time thorugh rest client tool, and server return the exception message.
I deployed my application in tomcat 7.x both windows and linux
Why it give the error when we hit the second time.
How to resolve this
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
#Override
public void filter(ContainerRequestContext requestContext) {
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
Error message:
Dec 19, 2016 6:26:18 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:147)
at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:803)
......
Please help me
Thanks in advance.
I Removed static variable
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
and i declared local variable. now its working fine.
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
#Override
public void filter(ContainerRequestContext requestContext) {
Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
You're trying to write in a response that was written before. The full log shows where is it happening. Upload the log and the code where the httpresponse is used/modified.

Pass FedAuth cookies from WebApi controller to RestSharp

We have a thinktecture powered identity server used for SSO. There are several services which utilize that identity server. My app uses ASP.net WebApi controllers to handle UI requests. For a particular request I have to make a REST API call to one of the mentioned above services. That service requires authentication of course. What I'm trying to do is to pass FedAuth cookies from the current request to RestSharp client:
[HttpGet]
[Route("api/testroute")]
public IHttpActionResult Test()
{
var client = new RestSharp.RestClient(_someBaseUrl);
var req = new RestSharp.RestRequest(_someUrl);
var cookies = Request
.Headers
.GetCookies()
.SelectMany(x => x.Cookies)
.Where(x => x.Name.StartsWith("FedAuth"))
.ToList();
foreach (var cookie in cookies)
{
req.AddCookie(cookie.Name, cookie.Value);
}
var resp = client.Execute(req);
return Ok(resp);
}
RestSharp client call fails with 500 error code with the following stacktrace inside:
[FormatException: Invalid length for a Base-64 char array or string.]
System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) +14390795
System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) +162
System.Convert.FromBase64String(String s) +56
System.IdentityModel.Services.ChunkedCookieHandler.ReadInternal(String name, HttpCookieCollection requestCookies) +424
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +99
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
Is my approach for user authorization correct? If so, am I doing something wrong with the cookies (from the stacktrace it looks like they are being corrupted)?
I think your FedAuth cookie was encoded. Maybe you can check if your FedAuth cookie contains char like '%'. If yes, just decode FedAuth before you use it.