I'm having trouble with making HTTP Requests using GWT 2.4 (and JQueryMobile jquery.mobile-1.0rc1.min.js, but not for anything related with the calls) on Phonegap 1.1.0. What I want to do is to use the POST method on another server in order to receive content and display it.
On the desktop it's working fine (thanks to a reverse proxy configuration). On Phonegap, I read that "the cross-domain security policy does not affect PhoneGap applications. Since the html files are called by webkit with the file:// protocol, the security policy does not apply.". However, it seems that the request is never made on the phone, as the response is empty and the status code 0 - a similar behavior that I experienced before I solved the cross domain issue on the desktop.
I'm using the regular RequestBuilder on GWT to send my requests. Any ideas on why this is happening? All the permissions on Phonegap are active.
edit: Here is my Java code that sends the request, from which I omitted my soap envelope:
RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,url);
rb.setHeader("SOAPAction", "assertIdentityWithSimpleAuthentication");
rb.setHeader("Content-type", "application/x-www-form-urlencoded");
String envelope = "etc"; //this is my soap envelope,
try{
rb.sendRequest(envelope, new RequestCallback() {
public void onError(Request request, Throwable exception) {
requestFailed(exception);
}
public void onResponseReceived(Request request, Response response) {
if(response.getStatusCode() == 200){
String aid = Tools.parseMessage(response.getText(),"assertionId"); //this just parses the response in order to get the string I need
Window.alert("Sucess: "+ aid);
sendAssertionID(aid); //and sends it to another function
}
else setError(response);
}
});
}
catch (RequestException ex) {
requestFailed(ex);
}
Check your url. Your code works fine on my android devices, but fails with an invalid url with code 0.
It needs to start with http:// or https://
Related
I am exploring/learning Spring security modules by implementing it through REST API.
To test the impact, we are using Postman native application as a rest client.
#RestController
#RequestMapping("/auth")
public class Employee {
#GetMapping("/status")
public ResponseEntity<String> getStatus()
{
ResponseEntity<String> responseEntity = new ResponseEntity<>("Resource is fetched", HttpStatus.OK);
return responseEntity;
}
}
above is a piece of resource for sake of consumption.
and below is the code snippet to configure Authentication and authorization
#EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("ashish").password("{noop}admin").roles("USER")
.and().withUser("foo").password("{noop}foo").roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/auth/status").hasRole("ADMIN").and()
.formLogin()
;
}
#Bean
public PasswordEncoder getPasswordEncoder()
{
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
now above authorization code is working fine when tried in browser - it uses its default spring login page.
however i am not quite able to understand how to execute/test the same through postman.
in method protected void configure(HttpSecurity http) , i tried removing formLogin() it did not work.
i added httpBasic - it also did not worked.
in postman, basic authentication is used by me.
while searching on internet, i came across some really good articles but almost all of them uses some sort of UI technology like angular or thymleaf to demonstrate the concept which i am finding hard to grasp.
I am referring below video tutorials to learn spring security.
https://www.youtube.com/watch?v=payxWrmF_0k&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=6&t=0s
Thanks in advance!
Ashish Parab
Do a GET request http://localhost:8080/login via postman and it will return you an html. Extract the _csrf token from the response. It will look like
<input name="_csrf" type="hidden"
value="1c470a6c-dff3-43aa-9d08-d308545dc880" />
Do a POST request as follows to http://localhost:8080/login, copying the _csrf token, username and password as form params
Take note of the JESSIONID Cookie value in the response from step two. And that is the session Id of the authenticated session.
As long as you sent the JESSIONID in subsequent requests as a cookie, spring security knows who you are. Postman will add that Cookie automatically to subsequent requests.
you can add it manually as header with that cookie header or update the postman settings to always send JESSIONID cookie
You will have to implement JWT token for the same and add it to the request header 'Authorization' in Postman. You can take a look at Java Brains Spring security videos on youtube.
I noticed yesterday that my Facebook login for my website has stopped working.
This has been working great for the last 2 months, as far as I am aware I have not changed anything. I have tried everything I can on links such as: - as well as many more...
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
I have noticed that the Stack Overflow Facebook auth has also stopped working.
Has anyone else noticed this and found any solution? It's worth noting I am using azure app services to host. But this issue is also found when I am using localhost.
My current setup looks like this...
in Startup.Auth.cs
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
{
AppId = "xxxxxxxxxxxxx",
AppSecret = "xxxxxxxxxxxx"
};
facebookOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookOptions);
In the following method, loginInfo is null every time.
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
I also added a session "WAKEUP" from a different post suggestion, fb auth failed once before and this fixed the issue this time, but it has come back.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
Session["WAKEUP"] = "NOW!";
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
As RockSheep explained. Facebook dropped the support vor API v2.2. You need to update your OWIN nuget packages.
You can find the issue on github (from the Katanaproject).
Ensure to activate pre releases in your nuget manager, than you are able to update the nuget packages to version v3.1.0-rc1. But beware: After the update, you need to test your login carefully (maybe you also have other authentication providers like Microsoft or Google, you should test them as well).
Technical
The Api changed the version number to v2.8 and the return value from the API is now in JSON-Format and no longer escaped in the URI. The 'old' OWIN packages can not handle this changes.
[Oauth Access Token] Format - The response format of
https://www.facebook.com/v2.3/oauth/access_token returned when you
exchange a code for an access_token now return valid JSON instead of
being URL encoded. The new format of this response is {"access_token":
{TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this
update to be compliant with section 5.1 of RFC 6749.
Here you can find the code-changes on GitHub for further informations and better understanding.
A lot of people started having trouble after yesterday. This is due to Facebook dropping support for v2.2 of their API. For some reason their system still redirects auth calls that don't use a version number to the 2.2 API. A quickfix is to ensure that the API version gets sent with the API call.
Starting at v2.3 Facebook also started returning JSON objects. So make sure to change that in the code as well.
I had the same issue, found solution here Fix facebook oauth 2017
Basically, you need to extend HttpClientHandler and decode JSON response instead of body
Here is a solution for those who are using scribe java.
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
JSONObject obj = new JSONObject(response);
return new Token(obj.get("access_token").toString(), EMPTY_SECRET, response);
}
Create a new class and set the extractor to JSON.
import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
public class FaceFmApi extends DefaultApi20 {
#Override
public String getAccessTokenEndpoint()
{
return "https://graph.facebook.com/oauth/access_token";
}
#Override
public AccessTokenExtractor getAccessTokenExtractor()
{
return new JsonTokenExtractor();
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
return null;
}
}
and inject your newly created class as below. Then getAccessToken() will work as expected.
public OAuthService getService() {
return new ServiceBuilder().provider(FaceFmApi.class)
.apiKey(config.getApiKey()).apiSecret(config.getApiSecret())
.callback(config.getCallback()).build();
}
What do we need : How to execute a external POST request on any page?
Why do we need : We are developing a secured intranet portal using Adobe CQ for our client. Any request for any page of Adobe CQ of intranet portal redirects to client's interface. This is an external system which generates a TOKEN and sends this token to CQ as an request parameter via HTTP request with POST method.
We set our cookies based on this token which needs to be part of every page. ( We are using page component inhertiance and setting them on root level)
Need suggestions on how this can be achieved. Let me know if more details are needed.
You can defined what method your servlet accepts, so the GET can be handled with a JSP and the POST with a SlingAllMethodsServlet.
#Component(metatype = false)
#SlingServlet(resourceTypes = "cq:Page", methods = "POST", generateComponent = false)
public class MyPOSTServlet extends SlingAllMethodsServlet {
#Override
protected void doPost(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException,
IOException {
//your logic here
}
}
This should get triggered for all pages.
Regarding your comment below your question, never have a servlet path with /content. Either a fixed virtual path like /bin/myservlet or a resourceType.
Check the documentation from Sling: https://sling.apache.org/documentation/the-sling-engine/servlets.html
Well i developing a Flex desktop app and i cant logout form facebook. I mean after loggin in and updating the photo i want to update, i run the method to log out, which looks like this
FacebookDesktop.logout(handleLogout);
Where handleLogout is a function where i can do other things.
The method runs but never log out. I think that maybe loading an other request i could log out, and i find that using:
"https://www.facebook.com/logout.php?" + info.get_accessToken() +
"&next=http://www.Google.com"
would log out, but i dont know where i ca get the accesToken.
Thanks in advance!
The following code is implemented in for asp.net page using C# code.
EXPLANATION
First you need to send a request to authenticate the user(the IF part). You will get a "CODE" on successfull authentication. Then send a request with this code to authorize the application. On successful authorization you will get the access token as response.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
Response.Redirect("https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&redirect_uri=CURRENT_URL&client_secret=APP_SECRET&code="+Request.QueryString["code"]);
}
else
{
Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=CURRENT_URL&scope=read_stream");
}
}
HERE IS THE PROCEDURE
Create an asp.net website
In the default.aspx page implement the above code.
Replace CLIENT_ID,APP_SECRET with the AppId and AppSecret respectively
CURRENT_URL should be the url of the page in which you are implementing the code.
The part "&scope=read_stream" is not mandatory. If you need any additional permissions please enter it here as comma separated values.
You will get a string in the format
access_token=ACCESS_TOKEN_VALUE&expires=EXPIRY_TIME
as response.
Try this to send a POST request using flex
var urlLoader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN");
request.data = binaryData;
request.method = URLRequestMethod.POST
urlLoader.load(request);
I am trying to use GWT to download the source code of web pages, but i do not know where to start, can anyone gives me some key word that i can search on google, or gives me some links from tutorials.
Thanks!!
In JavaScript, this is typically done with an XMLHttpRequest. GWT's analog to XMLHttpRequest is RequestBuilder, which can be used like so:
new RequestBuilder("GET", "http://example.com/page.html").sendRequest("", new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String src = response.getText();
// do things with the source
}
#Override
public void onError(Request request, Throwable throwable) {
// handle the error
}
});
Some GWT manual about cross-site scripting
https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite
And here some discussion about using RequestBuilder and JSNI
GWT RequestBuilder - Cross Site Requests
As alternative you can do a page download on the server-side...