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"
/>
Related
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
}
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");
}
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?
I am using linq to entity connection. I want to keep user logged in once he entered into his account, This is my code. It's not working. Help, please
if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
{
HttpCookie cookie = new HttpCookie(TxtUserName.Text, TxtPassword.Text);
cookie.Expires.AddYears(1);
Response.Cookies.Add(cookie);
}
if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
{
int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(TxtUserName.Text, TxtPassword.Text);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);// Not my line
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
Go to your web.config and find the authentication element. You can set the cookie expiration time (in minutes) there, like such:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login"
name="myCookie" <!-- optional, if you want to rename it -->
timeout="2880" /> <!-- expires in 48 hours -->
</authentication>
</system.web>
Source: how to apply "Remember Me" in c#
Hope this helps
Happy Coding..!!
I recommend to use MembershipReboot for authentication purposes in your app (samples are included).