Redirect to external URL with basic Authentication in MVC

Asked

Viewed 577 times

4

I am developing a C# MVC3 portal and in a given operation I need to open another portal in a separate window. To open the page of this new portal I need to send some credentials, since this is implemented with basic Authentication.

I would like to know how I can do it. I have tried it on controller:

var request = (HttpWebRequest)WebRequest.Create(redirectUrl);

request.Method = "GET";
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;

var cred = new NetworkCredential("user1", "pass123");
var cache = new CredentialCache();
cache.Add(new Uri(redirectUrl), "Basic", cred);

request.Credentials = cache;
var response = (HttpWebResponse) request.GetResponse();

return Redirect(response.ResponseUri.ToString());

What’s the best way to do this?

  • You can’t do that. The best you can do is ask that URI by passing the credentials and returning the answer instead of redirecting.

  • cannot set the cookie and then open the page ?

1 answer

1

It is not possible , since you would need to generate the exact cookie for the portal you are trying to access.

If the credentials are the same as your portal, you could do something like:

HttpWebRequest req =     (HttpWebRequest)WebRequest.Create(uri); 
// Add the current authentication cookie to the request 
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
Cookie authenticationCookie = new Cookie( FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority); 
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie); 
WebResponse res = req.GetResponse();

But I believe that this is not your case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.