Solved

Generate an ICredentials object from HttpContext.Current

Posted on 2009-05-12
3
6,480 Views
Last Modified: 2012-05-06
I have a Solution with two Web Applications.  A page (pageA) in Web Applications A needs to display the content from a page (pageB) in Web Application B.  I set up this up as so:

public class pageA : System.Web.UI.Page
{
protected override Page_Load(object sender,EventArgs e)
{
System.Net.WebClient client = new WebClient();
Stream htmlStream = client.OpenRead("http://localhost/WebApplicationB/pageB.aspx");
Response.Write(new StreamReader(htmlStream).ReadToEnd());
}
}

Everything works fine if WebApplicationB is set up in IIS for anonymous access.  However, I need to set up the site to use Basic Authentication.  When WebApplicationB requires authentication, my code above will throw a WebException saying a 401 unauthorized HTML status code was returned.  This is to be expected as my WebClient object isn't passing any credentials.

If I modify the code as so:
System.Net.WebClient client = new WebClient();
client.Credentials = new NetworkCredential("validUserName","validPassword");

Everything is happy again.  

However, I don't want to hard code a username / password and I don't want to store it in a web.config or other settings file.  Since my WebApplicationA is using the same authentication as WebApplicationB is there a way to get the Identity of the user making the request to WebApplicatioA\PageA and use that to build a NetworkCrendential or ICredentials object?  

In other words,

System.Net.WebClient client = new WebClient();
client.Credentials = (NetworkCredential)HttpContext.Current.Request.User;

Thanks,

PJ
0
Comment
Question by:ppittle
3 Comments
 
LVL 13

Accepted Solution

by:
dungla earned 400 total points
ID: 24372343
You should use the DefaultCredentials,which are the credentials of the currently logged on user. To do this, set the UseDefaultCredentials property to true instead of setting this property.
0
 
LVL 18

Assisted Solution

by:carlnorrbom
carlnorrbom earned 100 total points
ID: 24372444
Hi,
I agree with dungla. Because a straight forward implementation of actually retrieving the password for the logged in user would mean to either put some on-the-fly decryption mechanism or storing the passwords in plain text. You also need to allow for password retrieval. See attached code snippets for that type of implementation.
/Carl.

Code-behind:
 

protected override void OnLoad(System.EventArgs e) 

{ 

    System.Net.WebClient client = new System.Net.WebClient(); 

    if (User.Identity.IsAuthenticated) { 

        MembershipUser u = Membership.GetUser(User.Identity.Name); 

        client.Credentials = new Net.NetworkCredential(u.UserName.ToString(), u.GetPassword("PasswordQuestionAnswer")); 

    } 

    Stream htmlStream = client.OpenRead("http://localhost/WebApplicationB/pageB.aspx"); 

    Response.Write(new StreamReader(htmlStream).ReadToEnd()); 

} 
 

Web.Config:
 

  <membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="15" hashAlgorithmType="">

    <providers>

      <clear />

      <add connectionStringName="LocalSqlServer" enablePasswordRetrieval="true" enablePasswordReset="true"

      requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear"

      maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1"

      passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

    </providers>

  </membership>

Open in new window

0
 
LVL 8

Author Closing Comment

by:ppittle
ID: 31580593
Thanks!!  Guess I should have RTFM before posting the question =p
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
XML to SQL Table using c# 5 46
asp.net bundle 8 36
cs.Designer Issue 2 18
c# if statement weird reaction 3 29
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now