views:

267

answers:

8

Is it possible to create a .NET equivalent to the following code?

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.

A: 

Yes, you can add to web.config and use forms authentication. I dont know php, so i cant help witjh the rest of your question

http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx\

mattlant
A: 

Yes, but can you create a login dialog box with Forms authentication?

Akira
That would be an IIS setting. Basic authentication IIRC.
leppie
A: 

Yes, you can specify credentials in the web.config. ASP.NET also has a built-in membership system and has controls like Login to work with it - although this is different from setting static credentials in the web.config.

I think the easiest way to do what you're talking about is to protect the directory in IIS.

palmsey
A: 

I typically do my own authentication is asp.net against my own username and passwords in a database. For the way I do it, I create a username and password dialog on a page, and have a login button. During postback i do something like:

if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))
{
    FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}

Do with that in mind all you need to do is the same, check the username and password against whatveer you want, you can even hardcode if you want buy i wouldnt recommend it. \if its valid use the formsauthentication class's static methods.

mattlant
A: 
Akira
A: 

I am afraid I cant help you. I dont know how to get a dialog like that besides using a different security setup in IIS, such as integrated security (windows security). If that is all you want then you need to go into IIS and disable anonymous access, enable another auth type, such as integrated, basic,, and in your code you can verify they are logged in by checking:

System.Security.Principal.WindowsIdentity.GetCurrent().IsAuthenticated

Although IIS takes care of verification in this case. Other than that i cant help you out.

In case you need it, a link to windows auth in asp.net: http://msdn.microsoft.com/en-us/library/ms998358.aspx

mattlant
+1  A: 

The easiest way to achieve the same as with the PHP code would be to directly send the same headers via Reponse.AppendHeader().

Still I would suggest you to read an ASP.NET Forms Authentication Tutorial.

VVS
+1  A: 

You need to implement basic authentication in ASP.NET not forms authentication as the above responders said. A good example can be found here .

Andrei Rinea