This question already has answers here:
How to create asp.net web page with basic authentication
(1 answer)
Simplest way to add Basic authentication to web.config with user/pass
(1 answer)
Closed 2 years ago.
I want to implement a basic authentication in .net. So here i dont want an aspx page.
I only need web.config file and that should ask me for username and password( if i am not wrong we can have browser asking for username and password.)
Currently i have the below code which needs login.aspx page which i want to remove.
<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
<compilation debug="false" />
<authentication mode="Forms">
<forms>
<credentials passwordFormat="Clear">
<user name="abc" password="abc#123" />
</credentials>
</forms>
</authentication>
<!-- Unless specified in a sub-folder's Web.config file,
any user can access any resource in the site -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
<add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
<remove name="UrlAuthorization" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
</modules>
</system.webServer>
</configuration>
This isn't done in your application.
This is done in IIS, where you enable basic authentication and disable anonymous authentication.
But if you insist on doing it in code, you can add a HTTP-module, where you can check for basic authentication yourselfs.
E.g.
class SurroundingClass
{
public void ProcessRequest(HttpContext context)
{
if (!Authenticate(context))
{
context.Response.Status = "401 Unauthorized";
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", "Basic");
// // context.CompleteRequest();
context.Response.Flush();
context.Response.End();
return;
}
} // ProcessRequest
private static string[] ParseAuthHeader(string authHeader)
{
// Check if this is a Basic Auth header
if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic"))
return null;
// Pull out the Credentials with are seperated by ':' and Base64 encoded
string base64Credentials = authHeader.Substring(6);
string[] credentials = System.Text.Encoding.ASCII.GetString(System.Convert.FromBase64String(base64Credentials)).Split(':');
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0]))
return null;
return credentials;
} // ParseAuthHeader
private static bool TryGetPrincipal(string[] creds, ref System.Security.Principal.IPrincipal principal)
{
if (creds[0] == "Administrator" && creds[1] == "SecurePassword")
{
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("Administrator"), new string[] { "Administrator", "User" });
return true;
}
else if (creds[0] == "JoeBlogs" && creds[1] == "Password")
{
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("JoeBlogs"), new string[] { "User" });
return true;
}
else if (!string.IsNullOrEmpty(creds[0]) && !string.IsNullOrEmpty(creds[1]))
{
// GenericPrincipal(GenericIdentity identity, string[] Roles)
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(creds[0]), new string[] { "Administrator", "User" });
return true;
}
else
principal = null;
return false;
} // TryGetPrincipal
// http://blogs.msdn.com/b/odatateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx
public static bool Authenticate(HttpContext context)
{
// DANGER: On the developer system, we need to be able to test it without SSL certificate
// If Not context.Request.IsSecureConnection Then
// Return False
// End If
string authHeader = context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authHeader))
return false;
string[] credentials = ParseAuthHeader(authHeader);
System.Console.WriteLine(credentials);
System.Security.Principal.IPrincipal principal = null;
if (TryGetPrincipal(credentials, ref principal))
{
HttpContext.Current.User = principal;
return true;
}
return false;
} // Authenticate
}
Related
My application contains the roles "Admin" and "Users". How can I provide web.config setting for "users" with one default URL & "admin" with another default URL in web.config file.
My current web.config file code :
<authentication mode="Forms">
<forms defaultUrl="/Welcome.aspx" loginUrl="/LogIn.aspx" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
My aspx.cs code under login with condition :
if (res =="USER")
{
Details det = new Details();
int id = det.UserId(Email, Passwor);
Label2.Text = id.ToString();
Session["ID"] = Label2.Text;
string name = det.UserName(Email, Passwor);
Label3.Text = name;
Session["Name"] = Label3.Text;
Session["Role"] = TextBox1.Text;
Response.Redirect("Welcome.aspx");
}
if (res =="ADMIN")
{
FormsAuthentication.GetRedirectUrl(Email,true);
//Response.Redirect("admin_page.aspx");
}
I have https website and I am using membership for logins and
my code in controller:
int timeout = rememberme ? 2880 : 2; // Timeout in minutes,525600 = 365 days
var ticket = new FormsAuthenticationTicket(username, rememberme, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);//My Line
Response.Cookies.Add(cookie);
string returnurl = FormsAuthentication.GetRedirectUrl(username, rememberme);
if (string.IsNullOrEmpty(returnurl)) returnurl = "/Panel/Login";
if (string.IsNullOrEmpty(returnurl)) returnurl = "/Panel/Login";
if (rol == "User")
return Redirect("/Panel/Dashboard");
else if (rol == "Admin")
return Redirect("/Panel/DashboardAdmin");
return View();
and in we.config:
<httpRuntime targetFramework="4.6.2" executionTimeout="100000000" maxRequestLength="2147483647" />
<authentication mode="Forms">
<forms loginUrl="~/Panel/Login" requireSSL="true" slidingExpiration="true" />
</authentication>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
so its just keep login for 2 minutes and remember me is not working
what should I do?
we should add this to system.web in web.config file
an U can generate this key in iis but if U can access to iis U can use this code
<machineKey
decryptionKey="1513F567EE75F7FB5AC0AC4D79E1D9F25430E3E2F1BCDD3370BCFC4EFC97A541"
validationKey="32CBA563F26041EE5B5FE9581076C40618DCC1218F5F447634EDE8624508A129"
decryption="AES"
validation="SHA1"
/>
I have a .net 2.0 application using Forms Authentication with AD and have a directory for documents which has been configured using a web.config file -
<system.web>
<authorization>
<deny users="?"/>
<allow roles="Security Alerts - Admin"/>
<deny users="*"/>
</authorization>
</system.web>
When testing locally if I run the app and put the FQDN for a document /site/documents/Document1.pdf I am returned to the login page but when I have the site on a server I am able to open the PDFs without any problem. How can I force this so that if a user was to saves the URL of a document and tried to access it directly they would be forced to the login page to authenticate themselves first?
I have the same config for an ADMIN folder which includes aspx pages and works correctly and directs the users the Login page first, is it something to do with the doc type being a pdf as opposed to aspx pages.
Thanks in advance.
By default, .NET authentication does not work on static files such as pdfs.
You need to implement an HTTP Handler to serve your files if the user is authenticated.
It sound like your current authentication is set up and working correctly, so I won't go over the basics of setting that up.
Below is the relevant code which applies to your scenario taken from Kory Becker's helpful article here:
http://www.primaryobjects.com/2009/11/11/securing-pdf-files-in-asp-net-with-custom-http-handlers
You'll obviously have to alter the paths, namespaces and logic to suit your environment (e.g. IIS version) and/or specific file type requirements.
Step 1 - Create a FileProtectionHandler class which implements IHttpHandler
public class FileProtectionHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
switch (context.Request.HttpMethod)
{
case "GET":
{
// Is the user logged-in?
if (!context.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
return;
}
string requestedFile = context.Server.MapPath(context.Request.FilePath);
// Verify the user has access to the User role.
if (context.User.IsInRole("Security Alerts - Admin"))
{
SendContentTypeAndFile(context, requestedFile);
}
else
{
// Deny access, redirect to error page or back to login page.
context.Response.Redirect("~/User/AccessDenied.aspx");
}
break;
}
}
}
public bool IsReusable { get; private set; }
private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
{
context.Response.ContentType = GetContentType(strFile);
context.Response.TransmitFile(strFile);
context.Response.End();
return context;
}
private string GetContentType(string filename)
{
// used to set the encoding for the reponse stream
string res = null;
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
switch (fileinfo.Extension.Remove(0, 1).ToLower())
{
case "pdf":
{
res = "application/pdf";
break;
}
}
return res;
}
return null;
}
}
Step 2 - Add the following sections to your web.config file (with appropriate path/namespace modifications)
<httpHandlers>
...
<add path="*/User/Documents/*.pdf" verb="*" validate="true" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" />
</httpHandlers>
<system.webServer>
...
<handlers>
<add name="PDF" path="*.pdf" verb="*" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" resourceType="Unspecified" />
...
</handlers>
</system.webServer>
My login is..at controller
MemberShipProvider objMProvider = new MemberShipProvider();
var abc =RedirectToAction("Index", "Home");
if (ModelState.IsValid)
{
var checkVal = objMProvider.ValidateUser(m.username, m.password);
if (checkVal == true)
{
Session["User"] = m.username;
TempData["userName"] = m.username;
//IdentityHelper.RedirectToReturnUrl("~/User_Dashboard.aspx");
abc=RedirectToAction("Dashboard","User");
}
else if (checkVal == false)
{
abc = RedirectToAction("Index", "Home");
return abc;
}
}
my webconfig membership setting...
<system.web>
<membership defaultProvider="MemberShipProvider">
<providers>
<clear/>
<add name="MemberShipProvider" type="FndooMvc.Models.Common.MemberShipProvider"
connectionStringName="mycon"
applicationName="/" />
</providers>
</membership>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
my custom membership provider logincheck code is
public override bool ValidateUser(string username, string password)
{
return objLogin.IsValid(username,password) == true ? true : false;
}
i used flat login code then i decided to use custom membership as per demand. help me use this identity and principle feature with this custom membership
for now i want to know why my request.IsAuthenicated
have a look at this :
The ASP.NET Identity system is designed to replace the previous ASP.NET Membership and Simple Membership systems. It includes profile support, OAuth integration, works with OWIN, and is included with the ASP.NET templates shipped with Visual Studio 2013.
and if you want a good article in identity and principle feature
i needed this code block in global config in authenticate request event.
HttpCookie authCookie =Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { ',' });
GenericPrincipal userPrincipal =
new GenericPrincipal(new GenericIdentity(authTicket.Name),
roles);
Context.User = userPrincipal;
}
now request.isAuthenticated works.
how ever i am gonna change this provider and use as Hboubati suggested.
I'm trying to create a basic role based user access via FormsAuthenticationTicket but it's not working correctly as it doesn't seem to be passing the role to the page. The code I'm using is:
web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="HRPages">
<system.web>
<authorization>
<allow roles = "HR" />
<deny users ="*" />
</authorization>
</system.web>
</location>
<location path="SalesPages">
<system.web>
<authorization>
<allow roles = "Sales" />
<deny users ="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms" />
</system.web>
</configuration>
Login Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace formlogin
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdLogin_Click(object sender, EventArgs e)
{
if (this.txtUsersname.Text.Trim() == "1"
&& this.txtPassword.Text.Trim() == "2")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
this.txtUsersname.Text.Trim(), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
"HR", // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
// Redirect to requested URL, or homepage if no previous page
// requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "/";
// Don't call FormsAuthentication.RedirectFromLoginPage since it
// could
// replace the authentication ticket (cookie) we just added
Response.Redirect(returnUrl);
}
else
{
// Never tell the user if just the username is password is incorrect.
// That just gives them a place to start, once they've found one or
// the other is correct!
Response.Write( "Username / password incorrect. Please try again.");
}
}
}
}
When I go to a page under the HRPages folder it presents me with the login screen and on successful login it creates a ticket and redirects me back to the page but then reverts back to the login screen again. What am I doing wrong please as it seems as if the role isn't being passed through?