returnUrl drops second querystring parameter - asp.net

I am using MVC 5. The problem is that after SSO redirects back to the app after authentication the login method returnUrl drops the applicaitonId querystring parameter. Please help!
Here is the flow.
The app redirects unauthorized users to a login method, preserving the original request in the returnUrl.
The original request is
http://localhost:25451/shared/download?documentGroup=133&applicationId=3153
the returnUrl is
/shared/download?documentGroup=133&applicationId=3153
The app redirects to a SSO CAS server, sending along the HttpUtility.Encode returnUrl as a parameter along with login Url both part of the service parameters.
https://{redacted}/cas/login?service=http://localhost:25451/account/login%3freturnUrl%3d%2fshared%2fdownload%3fdocumentGroup%3d133%26applicationId%3d3153
After authentication, the CAS server appends the authorized ticket and redirects back to the service URL. This is what fiddler shows.
http://localhost:25451/account/login?returnUrl=/shared/download?documentGroup=133&applicationId=3153&ticket={redacted}
Here is the issue. The returnuRL in the login method is simply
/shared/download?documentGroup=133.
The returnUrl no longer has the applicationId.
Interestingly enough, the line works just fine.
var ticket = Request.QueryString.Get("ticket");
I have tried to encode the whole serviceUrl and tried to encode just the returnUrl(see below) but I get the same missing ApplicationId issue.
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
var ticket = Request.QueryString.Get("ticket");
if (!string.IsNullOrEmpty(ticket))
{
//verify the ticket...
return RedirectToLocal(returnUrl);
}
var serviceUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port) + "/account/login" + "?returnUrl=" + HttpUtility.UrlEncode(returnUrl);
var authenCasUrl = string.Format("{0}login?service={1}", "https://{redacted}/", serviceUrl);
return Redirect(authenCasUrl);
}

Since this site will be actually called by your URL, I don't think they just throw away parts of it.
Lets try something here since I have encountered a similar problem with parameter in url strings in combination with asp.NET.
First, lets get the unedited URL from your Request:
string UneditedUrl = Request.RawUrl;
Since we are not needing anything before the ? mark, we shorten it a little bit:
string QueryString = (UneditedUrl.IndexOf('?') < UneditedUrl.Length - 1) ? UneditedUrl.Substring(UneditedUrl.IndexOf('?') + 1) : String.Empty;
This line also includes the possibility on neither having a ? mark or parameters and will return an empty string if so. Just for good measure, we don't want any exceptions here. Here you can check QueryString if it has both or more of your parameters you entered.
If there are not complete here, its not your code at fault. Something will already work on your URL before you do, probably your host then. Maybe check the settings of your IIS.
If your parameters are correctly in the edited QueryString, you can continue getting them by following this:
I learned that there is a way to let your framework do the job of parsing parameters into name/value collections. So lets give it a go:
NameValueCollection ParaCollection = HttpUtility.ParseQueryString(QueryString);
You can now check you params and their values by either using an index like ParaCollection[0] or ParaCollection["documentGroup"].
EDIT:
I've found the question which brought me to the conclusion of using Request.RawUrl. Since this may not be the answer, it will maybe help a little bit more to understand that Request.RawUrl is the actual URL the user called and not the one the server executes: RawURL vs URL

I have no experience with asp or SSO, but you may need to also HttpUtility.UrlEncode the value of the serviceUrl variable?
var authenCasUrl = string.Format("{0}login?service={1}", "https://{redacted}/", HttpUtility.UrlEncode(serviceUrl));
Since the service parameter is decoded by the CAS once, and then the value of returnUrl gets decoded by your server.
var returnUrl = "/shared/download?documentGroup=133&applicationId=3153";
var serviceUrl = "http://localhost:25451/account/login?returnUrl=" + HttpUtility.UrlEncode(returnUrl);
var casUrl = "https://{redacted}/cas/login?service=" + HttpUtility.UrlEncode(serviceUrl);
Which gives:
serviceUrl = http://localhost:25451/account/login?returnUrl=%2Fshared%2Fdownload%3FdocumentGroup%3D133%26applicationId%3D3153
casUrl = https://{redacted}/cas/login?service=http%3A%2F%2Flocalhost%3A25451%2Faccount%2Flogin%3FreturnUrl%3D%252Fshared%252Fdownload%253FdocumentGroup%253D133%2526applicationId%253D3153
Explanation attempt:
You make a HTTP request to the CAS server. It's implementation splits the query parameters and decodes each value (and possibly key). One of which is the service parameter and is now (after decoding) a valid URL.
The CAS server makes a HTTP request with the URL from the service parameter (to your server) with the ticket appended.
You split the query parameters and decode each value (and possibly key).
If you only encoded the returnUrl once, your serviceUrl will look like what you showed in your third point:
http://localhost:25451/account/login?returnUrl=/shared/download?documentGroup=133&applicationId=3153&ticket={redacted}
How does the algorithm splitting the query string differentiate between a ? or & in the serviceUrl and the ones in the returnUrl?
How should it know that ticket does not belong to the returnUrl?
As you can see in my code above, you are not encoding the returnUrl twice.
You are putting one URL in the parameters of another URL and then you put that URL in the parameters of a third URL.
You need to call UrlEncode for each value (and possibly key) when you put together a query. It does not matter whether that value is a URL, JSON, or arbitrary user input.

Related

HTTP get request won't submit with a URL encoded parameter

I'm currently writing an ASP.NET Core web API that has an action with a encrypted value as a parameter.
I'm trying to test this action and the URL won't even submit in the web browser, at first I thought it could be due to the URL being too long but I've found this answer and my URL is well below the 2000 character limit. I've changed the parameter to a trivial string ("hello") and it submits fine and runs the code. I've tried in both Edge and IE11 whilst debugging my application, in Edge nothing happens at all, in IE11 I get a message saying:
Windows cannot find 'http://localhost:5000/api/...' Check the spelling and try again
In either case the code in the application doesn't execute (I've put a breakpoint on the first line of the controllers constructor which isn't being hit).
I've included an example of one of the URLs that isn't working below, as well as the code I'm using to generate the encrypted string, it uses HttpUtility.UrlEncode to convert the encrypted byte[] array to a string.
Example URL (one that doesn't work):
http://localhost:5000/api/testcontroller/doaction/%95%d6%f8%97%84K%1f%d4%40P%f0%8d%de%27%19%ed%ffAR%9c%c6%d4%b1%83%1e%9fX%ce%9b%ca%0e%d4j%d3Rlz%89%19%96%5dL%b1%16%e9V%14u%c7W%ee%89p%3f%f7%e6d%60%13%e5%ca%00%e9%a2%27%cb%d3J%94%a6%e1%b9%9c%914%06y%7e%0bn%ce%00%e5%7d%98b%85c%fa6m%7d%f7%f1%7b8%26%22%5e%1et%5e%10%0c%05%dd%deFAR%bb%93L%b9-W%e1K%82%d8%cc8%ce%e0%0c%2b%bc%19
Action:
[HttpGet("[action]/{encrypted}")]
public string DoAction(string encrypted)
{
return "Executed";
}
Generate encrypted string:
private string GenerateEncryptedString()
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
byte[] data = HttpUtility.UrlDecodeToBytes("AHMW9GMXQZXYL04EYBIW");
byte[] encryptedData = rsaProvider.Encrypt(data, true);
string encryptedString = HttpUtility.UrlEncode(encryptedData);
return encryptedString;
}
Not sure if I'm going wrong in my methodology for converting the encrypted data to a string but I would appreciate any feedback on how to fix this issue.
I think you should try to pass this data in the query string and not in the location (path) part of the url (some characters may be forbidden in paths as a security layer), so add a ?data= before the encoded data.
http://localhost:5000/api/testcontroller/doaction/?data=%95%d6%f8%97%84K%1f%d4%40P%f0%8d%de%27%19%ed%ffAR%9c%c6%d4%b1%83%1e%9fX%ce%9b%ca%0e%d4j%d3Rlz%89%19%96%5dL%b1%16%e9V%14u%c7W%ee%89p%3f%f7%e6d%60%13%e5%ca%00%e9%a2%27%cb%d3J%94%a6%e1%b9%9c%914%06y%7e%0bn%ce%00%e5%7d%98b%85c%fa6m%7d%f7%f1%7b8%26%22%5e%1et%5e%10%0c%05%dd%deFAR%bb%93L%b9-W%e1K%82%d8%cc8%ce%e0%0c%2b%bc%19

UserManager.GenerateEmailConfirmationToken returning tokens unsuitable for URL transmission

I have a ASP.NET MVC 5 website, and I'm implementing an email confirmation process based on the template from Microsoft.
While I'm composing the email body text, first I construct the URL a user will use to "click to verify your address".
To generate the security token I call:
UserManager.GenerateEmailConfirmationTokenAsync(user.Id)
This produces a code such as:
pporPNj6KzdZ3BYG8vQsKJu3dPJMwGgh+ZEGhCNnf9X6F0AS0f6qCowOQwQNfpYkl14bgEsmyPTKya5H6N4n2na2n5PgO+wpoihXxQTA7G8pK/lUYskX3jy2iA/ZM8m4Vm0prTyUuhMgfDlV+wkbR336FBRIAbKJDwOWvHHbJBDQ21gW93hyzca0li66aI1H
Obviously, this wouldn't be valid in a URL, but even URL encoding won't solve IIS's hate of such a URL.
HTTP Error 404.11 - Not Found
The request filtering module is configured to deny a request that contains a double escape sequence.
In my UserManager implementation, I'm using the tutorial boilerplate code for a TokenProvider.
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<SiteUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
How can I make these generated tokens a bit more URL friendly? What did potentially change that would prevent the ASP.NET's tutorial code not work?
It turns out that this token will get mangled by the built in class "UrlHelper" in a MVC controller, or Url in a WebAPI controller IF the target route lists these variables as part of the path, rather than the GET vars of the URL.
Eg: this call, creates a relative URL for the site route called "ConfirmEmail" and fills in the blanks
Url.Route("ConfirmEmail", new { userId = user.Id, code = code });
Before my route was:
[Route("register-email/{code}/{userId}", Name = "ConfirmEmail")]
Changing this to:
[Route("register-email", Name = "ConfirmEmail")]
Generates valid URLS that IIS can chew through. When these are not specified, they get appended after a ? mark as normal GET vars. No idea why IIS is picky like that, but there's the solution.

Why google login redirect back to site with hashtag - can it be avoided

I didn't succeeded to find any relevant answer to this so I must ask :)
I implemented google plus login to my site. With a few workarounds it work fine but...
When I am redirected back to my site from google I am returned to the following URL:
http://localhost/mysite/west/Default.aspx#state=/profile&access_token=ya29.qQDrtcVtgOEbS86Bg10puFG3dksJz74BlrEGulHldlJW2o5qQ6g7ilF17zQsm8iMLG0C82PQyp2Z-g&token_type=Bearer&expires_in=3600
Because of this parameter here #state=/profile& I first have to read URL in javascript on load, remove this part to fix URL and then do this:
var url = "Default.aspx?" + queryString;
window.location = url;
And then I can continue to read query string normally in code.
I don't like this because when I do this I make two postback on page and I want to avoid this if possible.
Is this redirect url must have this or this can be avoided?
Redirect to google:
string url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&state=%2Fprofile&redirect_uri="+this.Return_url+"&response_type=token&client_id=" + this.Client_ID;
Response.Redirect(url);
When I get back to my site:
if (this.Request.QueryString["access_token"] != null)
{
String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();
WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URI);
Change response_type=token to response_type=code. The callback URL will then have a code query parameter which is accessible server side instead of a fragment. You will then have to implement step 4 to exchange the code for an access_token.

Get the full QueryString from URL in ASP.NET

I have an URL with the following format:
http://www.mysite.com/login.aspx?ref=~/Module/MyPage.aspx?par=1&par2=hello&par3=7
I use the content of the QueryString it to Redirect the user back to the page he was before logging in. In order to keep also the status of the page I need the parameters in the QueryString. The number of parameters changes depending on the Page calling the Login and its status.
Let's say I want to store everything in the URL after ref in the redirectURL variable. I tried:
redirectURL = Request.QueryString("ref") // "~/Module/MyPage.aspx?par=1"
it gets everything after ref but ignores everything after the &(included). If I use:
redirectURL =Request.Url.Query // "ref=~/Module/MyPage.aspx?par=1&par2=hello&par3=7"
it gets everything, ref included. In order to achieve my goal I need just to remove the first 4 characters from the redirectURL. But I think this solution is a bit "forced" and I am sure there should be some ASP.NET function that accomplish this task.
The &s in your URL are creating additional querystring arguments.
You need to escape the value of the ref parameter before putting it in the querystring.
This will replace the &s with %26.
To do this, call Uri.EscapeDataString().
When you fetch the property from Request.QueryString, it will automatically decode it.
Consider Encoding "~/Module/MyPage.aspx?par=1&par2=hello&par3=7" before passing it to the url.
Eg.:
String MyURL = "http://www.mysite.com/login.aspx?ref=" +
Server.UrlEncode("~/Module/MyPage.aspx?par=1&par2=hello&par3=7");
And then, you can get the redirectURL using:
String redirectURL = Request.QueryString("ref");

What is the use of =? in links?

I saw my friend doing some Web Development, and one of his code caught my attention is the Response.Redirect.
What is the use of Home?=, isn't it the LogIn.aspx is the name of the page how come it's still redirecting if it has Home?=. Can someone answer this question of mine please, and explain it very well.
String url = "LogIn.aspx?Home?=" + Username;
Response.Redirect(url);
Update
Working from all your comments, the answer is: The query string parameter name (key) is actually "Home?", not just "Home". Details (including why the code generating that is technically incorrect) below.
how come it's still redirecting if it has Home?=?
Because there's no reason it shouldn't redirect. Granted the URL is invalid (? is a reserved character, it cannot appear unencoded in the query string, so the second ? in the URL is incorrect), but browsers are pretty content to deal with invalid URLs.
Separately, unless Username has already been URL-encoded, the URL could have other errors depending on the content of Username. (All query string parameters must be URL-encoded, in .Net you do that with HttpUtility.UrlEncode.)
Re your comment:
what i mean is i don't know why he use Home?= and what is the use of it
It has no use, it's an error. He probably just meant (no, apparently not, see below after your next comment)
String url = "LogIn.aspx?Home=" + Username;
...which would more correctly be:
String url = "LogIn.aspx?Home=" + HttpUtility.UrlEncode(Username);
(Technically, you have to URL-encode both the keys and values [both "Home" and Username], but the URL-encoded form of "Home" is "Home", so we can get away without making the call for the key. Not true if the key needs to have any of the URL reserved characters in it.)
Re your further comment consisting entirely of this code:
string retrieveValue;
protected void Page_Load(object sender, EventArgs e) {
this.lblUsername.Text = Request.QueryString["Home?";
retrieveValue = this.lblUsername.Text;
}
Assuming the syntax error in the above is fixed (missing ] on line 3), it would appear that he's actually using "Home?" as a key (parameter name). That means the redirect should be:
String url = "LogIn.aspx?" + HttpUtility.UrlEncode("Home?") + "=" + HttpUtility.UrlEncode(Username);
...because the key has a reserved character in it (?). Because that will be decoded for you on receipt, that should make the code above work.
Note that most browsers will probably let you get away with the string as he specified it. It's incorrect, but in a way browsers probably allow.
Regardless of the errors that T.J covered, what he meant to do was load the page LogIn.aspx with the variable "Home" being set to the visitors username. This allows the page to "GET" the variable and use it. Its basically a way of sending data from one page to another.

Resources