Auth0 invalid state parameter in go lang - auth0

I have been following the Auth0 go example here, and it works fine when I am testing it locally, but when I deploy my test app, when going through the flow, I am getting an invalid state parameter.
I can see that the error is happening in this code block:
if r.URL.Query().Get("state") != session.Values["state"] {
// BUG it is failing here in prod
http.Error(w, "Invalid state parameter", http.StatusBadRequest)
return
}
If i highlight the URL in the browser, and press enter, the auth with work fine as expected and redirect me accordingly. It appears to me this is happening because the session cookie being generated by gorilla/sessions might not be ready on the first attempt, but on the second attempt it is, but this is a strict assumption.
I made sure that I am setting the pragma: no-cache header assuming that the browser, but thats not it.
Any ideas how to overcome this issue on a deployed app (the app is behind a https url).

Related

httpd/mod_auth_form How to display an error message on invalid credentials?

Using inline form with ErrorDocument 401, how can I get an error message to be displayed when the user fails to login?
Expected features are to still work (e.g. login redirect). No login/logout URLs seen in user's browser. When the user logs out, the message should not be shown when they are 401'd back to the inline login page.
I am currently using an onsubmit function to set a flag in sessionStorage. If the page loads (body onload function) and sees this flag, it will show the error message (e.g. user entered wrong credentials and are back here again). This works fine, until they logout. They are 401'd to the login page and the flag is still there, so they see the error message.
I need to clear the message somehow.
Well, GET vs POST! The initial page load is a GET and the logout is a GET; so, only failed logins would be loading this page with a POST.
Let's activate SSI and use an env var (this is on both login and logout Location directives):
SetEnvIf Request_Method "^GET$" LOGIN-ERROR-CLEAR="1"
Inject some JS to our init to clear the sessionStorage:
<!--#if expr="reqenv('LOGIN-ERROR-CLEAR') == '1'" -->
sessionStorage.removeItem('login-attempted');
<!--#endif -->
Sounds logical...but, it doesn't work. The JS is not injected.
GET /logout -> 307 to "/" (due to AuthFormLogoutLocation "/")
GET / -> 401 with content of /login.html
error message is wrongly shown
All GETs, yet the JS was not injected. What is going on? I am back where I started before using SetEnvIf - there is no difference. It's not doing anything!
Is there a better way to trigger an error message and clear the trigger after successful login or logout? This shouldn't be this hard!
Found out I could use the variables directly in the SSI; so, I removed the SetEnvIfs from my vhost. Also, REQUEST_METHOD is the wrong one to use. REDIRECT_REQUEST_METHOD is the one to look for. In the end, this seems to be working:
<!--#comment This block uses SSI/mod_include. -->
<!--#if expr='v("REDIRECT_REQUEST_METHOD") == "GET"' -->
sessionStorage.removeItem('login-attempted');
<!--#endif -->

Auth0 and angular2: how to set callbackURL and catch the token?

I am trying to implement passwordless authentication with Auth0 and angular2 (2.0.0-rc.6), using angular2-webpack-starter and auth0-lock-passwordless.
The form displays normally, and the authentication e-mail is sent using this code:
this.lock.magiclink({
callbackURL:"http://localhost:3000/#/sandbox"
});
The issues occur after I click the magic link in the e-mail:
Even though the redirect_uri of the magic link seems correct (redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F%23%2Fsandbox), it is ignored;
Instead, after a successful login (checked in Auth0 logs), the url in the address bar is (briefly):
http://localhost:3000/#access_token=xxxxxxxxxx&id_token=yyyyyyyyy&email=myemail#emails.com (notice the # instead of expected question mark)
then (after a second or so) it redirects to: http://localhost:3000/#/access_token
My questions are:
How to have Auth0 actually redirect to callbackURL?
How can I catch the token with the new angular2 router, even though the uri is misformed? (question mark missing before the query)
After much struggling, I found a workaround.
TL;DR; use PathLocationStrategy (HTML 5 pushState), not the "hash URL" style.
Below Allowed logout URLs and Allowed origins in the Auth0 console (Clients settings), it is specified:
Notice that querystrings and hash information are not taken into account when validating these URLs.
So I figured it might apply to Allowed Callback URLs as well, even though it was not specified.
That would explain why callbackURL is ignored.
The trick is then to get rid of the hash (#) in the URLs; the hash is the default LocationStrategy in Angular2 Webpack Starter.
To do that, in app.modules.ts, change RouterModule.forRoot(ROUTES, { useHash: true }) to RouterModule.forRoot(ROUTES, { useHash: false })
Although it should have worked, I came accross yet another issue: when you reload a page, it gives a blank page with the following message:
<% if (webpackConfig.htmlElements.headTags) { %>
After a little Googling, I found a fix in this page.
The fix is to remove the carret (^) in the "webpack-dev-server": "^2.1.0-beta.2" (devDependencies, package.json), and reinstall the package:
replace "^2.1.0-beta.2" by "2.1.0-beta.2"
then, in console/terminal, type: npm install webpack-dev-server
Now all I had to do was to update the callbackURL like so:
this.lock.magiclink({
callbackURL:"http://localhost:3000/sandbox"
});
And in Auth0 Clients settings' Allowed Callback URLs, insert:
http://localhost:3000/sandbox
and save.
Now, after a successful login (when I click the magic link in the e-mail), it opens a browser window with following URL:
http://localhost:3000/sandbox#access_token=xxxxxxxxxxx&id_token=yyyyyyyyyyy&token_type=Bearer
and it stays there, as it should. Catching and saving the token should now be trivial...

Postman Resolving "Invalid CORS request" for a POST Request

I've just started using Postman to test an API I am integrating to.
I have the following error that keeps showing up
Invalid CORS request
Note the following:
The API uses Bearer token authentication(OAuth2). I have this
working without a problem.
I do get the bearer token successfully, assign it to an Environment variable and then attempt to use it for the RESTful operations.
The problem is in the subsequent RESTful operation that uses the token.
When I use an old token (through a POST operation), it rightfully
tells me that it is expired and not authorized.
When I then generate a new one and try to run the restful call, it gives me that Invalid CORS request error.
Using cURL, I have no issues. But I am frustrated by Postman.
What I have found so far:
Using postman with Http POST requests - I don't get the part in bold
Just in case anybody else has this same problem, here is how to solve
it. Go to https://www.getpostman.com/docs/capture in your chrome
browser. Click on interceptor extension and then choose add to
chrome. Once it is added there is a new icon top right of both the
browser and postman that looks like a traffic light. In postman click
this and it turns green. Then add a header to every request going to
third light. Every header consists of the header name and a value.
Start typing over the header name and a list of allowed http headers
comes up. Choose "Origin". In the cell for value simply type the
full URL of your server. (Do not forget the 'http://' or 'https://').
What is the expected response to an invalid CORS request? - Best explanation I have seen so far on CORS errors.
The other material speaks about Access-Control-Allow-Method header, preflight requests
... and there is an illustrative Apache Tomcat flowchart of the CORS flow.
Here's the answer you found again:
Just in case anybody else has this same problem, here is how to solve it. Go to https://www.getpostman.com/docs/capture in your chrome browser. Click on interceptor extension and then choose add to chrome. Once it is added there is a new icon top right of both the browser and postman that looks like a traffic light. In postman click this and it turns green.
... With the bit in bold translated:
Then add a header to your request. The header Key should be "Origin" and the header Value should be the full URL of your server (Do not forget the http:// or https://).
Note that Chrome/Postman won't allow you to add a Header with a Key of Origin without the Interceptor plugin.
Also note that at least on my system the Interceptor icon no longer looks like a traffic light.
If your back-end service side code checks for origin of the request (just to avoid CORS attack) you may face this issues when testing your Rest API through postman.
How to Resolve this .?
You need to install a Chrome plugin called Postman Interceptor (https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo?hl=en).
After successfully installing this plugin , in you Postman client you can see small icon called Postman Interceptor , you need to toggle it to turn it on.
Now you can add a Request header as below
RequestHeader Key "Origin"
RequestHeader Value "your application base URL"
Check this image
Now you should be able to over come CORS issues you are facing
Cheers !!
Just avoid using browser/chrome postman plugin. Use the desktop application instead!
Seems our server is seeing from a Postman manual HTTP POST that the orgin is invalid b/c its coming from Postman as "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop"
Not sure why or how to resolve on client/Postman side. Seems our server is correclty rejecting it as is though and issuing a 403.
Value of "Origin" header set in Postman request should be allowed in API backend. For example, using Spring Boot for API should have next:
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Value("${cors.allowedOrigins}")
private String allowedOrigins;
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("*")
.allowedHeaders("*");
}
}
where allowedOrigins is set using application.properties property cors.allowedOrigins having comma separated list of allowed origins, eg:
cors.allowedOrings=http://localhost:8080,http://example.com
and set 'Origin' value in Postman to any url from cors.allowedOrigins
I was getting this error when testing my APIs on the postman. Even after meticulously configuring my cors. So I used Insomnia instead of Postman and it works fine. I guess sometimes postman is the problem as it needs some extra effort.
You can try new version of PostMan. To me it works after upgraded postman version from 5.5.5 to 7.36.5

Github api error redirect_uri_mismatch

I keep getting this same OAuth error when trying to work with the github api. Sometimes it goes away but most of the time it stays. I have tried resetting my secret key, revoking all tokens, clearing safari cache but no luck. This is the error : error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23redirect-uri-mismatch
All the forums say to fix this error, remove the redirect_uri parameter of my request which I have done.
This is my request: https://github.com/login/oauth/authorize?client_id=myclientid&scope=user,public_repo
Everything shows up and when I click authorize it redirects me back to my application but instead of giving me the code it gives me the error.
Either put http instead of https in your Authorization callback URL
in your GitHub OAuth apps settings.
http://www.example.com/oauth/complete/github/
Another Option
settings.py
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True

MalformedURLException in application tests

I'm working on application tests and have found an issue.
My app. has an authenticate(email, password) action inside the
Security controller and when invoked, from the login page, with a
valid e-mail and invalid password it sends me back to the login page
with an error message, located in the flash scope.
The app. test code follows :
Response response =
GET("/security/authenticate?email=validUser&password=invalid", true);
String pattern = "invalid password";
assertContentMatch(pattern, response);
When this code is run throws the next exception :
A java.lang.RuntimeException has been caught,
java.net.MalformedURLException: no protocol: /login
Did some research and found that :
the exception is thrown when a new URL object creation is attempted,
to be able for redirection, using an invalid URL. In this case no
protocol is present
looking at app. test in samples apps. GET is used without
redirection, meaning that after GET only the http code is verified but
no attempt to follow the redirection
Has anyone had this same issue also ?
Any open bug to look for info or add my 2 cents ?
Here you can find a description of the problem as well as code snippet to work around the issue:
https://play.lighthouseapp.com/projects/57987/tickets/1553-functionaltestget-with-redirect-crashes