I've a quick question and request you all to respond soon.
I've developed a web service with Form based authentication as below.
1.An entry in web.config as below.
<authentication mode="Forms">
<forms loginUrl="Loginpage.aspx" name=".AuthAspx"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<authentication mode="Forms">
<forms loginUrl="Loginpage.aspx" name=".AuthAspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
2.In Login Page user is validate on button click event as follows.
if (txtUserName.Text == "test" && txtPassword.Text == "test")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, // Ticket version
txtUserName.Text,// Username to be associated with this ticket
DateTime.Now, // Date/time ticket was issued
DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
false, // if user has chcked rememebr me then create persistent cookie
"", // store the user data, in this case roles of the user
FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket
Response.Cookies.Add(cookie);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "~/Default.aspx";
Response.Redirect(returnUrl);
}
3.Webservice has a default webmethod.
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
4.From a webApplication I am making a call to webservice by creating proxy after adding the webreferance of the above webservice.
localhost.Service1 service = new localhost.Service1();
service.AllowAutoRedirect = false;
NetworkCredential credentials = new NetworkCredential("test", "test");
service.Credentials = credentials;
string hello = service.HelloWorld();
Response.Write(hello);
and here while consuming it in a web application the below exception is thrown from webservice proxy.
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
Could you please share any thoughts to fix it?
You need to set
service.AllowAutoRedirect = true
If you are planning to redirect in your code.
Just tried this and worked: Go to the website where you are hosting the web service in IIS, click on Session State, change the Cookie Setting's Mode to Use Cookies. Done.
You need to set both
service.AllowAutoRedirect = true;
service.CookieContainer = new CookieContainer();
Related
i use this code for login user in my api:
var ticket = new FormsAuthenticationTicket(
1,
CurrentCustommer.PhoneNumber,
DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false,
"user,user1",
FormsAuthentication.FormsCookiePath
);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain
};
HttpContext.Current.Response.AppendCookie(cookie);
my webconfig code is:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="10080" slidingExpiration="true">
</forms>
</authentication>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" />
<pages enableSessionState="true" validateRequest="false"></pages>
<sessionState mode="InProc" cookieless="false" timeout="10080" />
now. user after login and after a few minutes and refresh page or change page in site, Automatically Log outed; I see cookies stored through the "document.cookie" in chrome console. this problem does not exist in local host but when used server this problem showed :/
Also, I add that I use my customized database and don't use sql membership provider asp.net.
Should I apply certain settings when I call the method API for user login? Or I need to apply other configurations?
Really I do not know how to fix this problem.
thanks all.
UPDATE: i check authenticate user by this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.User.Identity.IsAuthenticated)
{
//Page.Response.Redirect("/");
MainContainer.Visible = false;
Page.ClientScript.RegisterStartupScript(this.GetType(),
"CallMyFunction", "LoginForm()", true);
}
}
for more info And i now see Page.User.ExpireDate in watch in Page_Load, this time 30 minutes after login user.
cookieless="false" can you just try using cookieless property as default or true
If I want to set up a multidomain authentication (or for whatever other reason I want to specify the authentication domain) I have to do it in two places:
In the web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" enableCrossAppRedirects="true" domain="mydomain.com" />
On the login page, when I am creating my authentication cookie:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddHours(3), false, role, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Expires = ticket.Expiration;
cookie.Domain = "mydomain.com"; // <-----
Response.Cookies.Add(cookie);
That is fine... but whenever I want to change the domain I have to do it in two places. Is there a way to read the domain straight from the < authentication > tag in web.config? I know I could put it in the < appSettings > section and read it easily from wherever in the program, but then I would have to change it twice in the web.config file.
you can set it in authentication/forms and read it as FormAuthentication.CookieDomain
I had implemented custom asp.net authentication and added all the required attributes even then the user are signout frequently.
I had hosted this website on shared godaddy server.
Here is my code:
var ticket = new FormsAuthenticationTicket(2, auth.Message.ToString(), DateTime.Now, DateTime.Now.AddDays(3), true,
string.Empty, FormsAuthentication.FormsCookiePath);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
{
Domain = FormsAuthentication.CookieDomain,
Expires = DateTime.Now.AddYears(50),
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(auth.Message.ToString(), true));
My Web.config has these values:
<authentication mode="Forms">
<forms requireSSL="false" timeout="120" loginUrl="~/CRM/Logon.aspx" defaultUrl="~/CRM/OTP.aspx" />
</authentication>
My users are complaining that they are logged off around 10-20 minutes
Any help is appreciated.
EDIT
I had removed requireSSL="false" timeout="120" and even then no effect.
I am not using session as well
The problem is we need to specify Application Pool Idle timeout also to make the above conditions works.
I'm just creating a simple test between two server. Basically if a user has already authenticated I want to be able to pass them between applications. I changed the keys to hide them
I have three questions:
What is the proper way to validate the cookie across domain application. For example, when the user lands at successpage.aspx what should I be checking for?
Is the below code valid for creating a cross domain authentication cookie?
Do I have my web.config setup properly?
My code:
if (authenticated == true)
{
//FormsAuthentication.SetAuthCookie(userName, false);
bool IsPersistent = true;
DateTime expirationDate = new DateTime();
if (IsPersistent)
expirationDate = DateTime.Now.AddYears(1);
else
expirationDate = DateTime.Now.AddMinutes(300);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
userAuthName,
DateTime.Now,
expirationDate,
IsPersistent,
userAuthName,
FormsAuthentication.FormsCookiePath);
string eth = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, eth);
if (IsPersistent)
cookie.Expires = ticket.Expiration;
cookie.Domain = ".myDomain.com";
Response.SetCookie(cookie);
Response.Cookies.Add(cookie);
Response.Redirect("successpage.aspx");
}
My config:
<authentication mode="Forms">
<forms loginUrl="~/Default.aspx" timeout="2880" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
</authentication>
<customErrors mode="Off" defaultRedirect="failure.aspx" />
<machineKey decryptionKey="#" validationKey="*" validation="SHA1" decryption="AES"/>
What is the proper way to validate the cookie across domain application.
For example, when the user lands at successpage.aspx what should I be checking for ?
There shouldn't be anything to check. Forms authentication mechanism will retrieve the ticket from the cookie, check if it is valid. If not present, or invalid, user will redirected to ~/Default.aspx .
This will work provided your cookie matches the configuration of your web.config
Is the below code valid for creating a cross domain authentication cookie ?
I think you shouldn't try to override the settings of your web.config by manually handling the cookie. I think there are better ways for handling cookie persistence (see below for web.config) and you are just implementing a part of the Forms authentication API (loosing web.config for SSL for example )
here, your manual cookie is not HttpOnly : you could for example be subject to cookie theft through XSS
FormsAuthentication has its own way of handling the cookie (see the TimeOut attribute description in http://msdn.microsoft.com/en-us/library/1d3t3c61%28v=vs.80%29.aspx) Your cookie persistence mechanism will be overwritten by this automatic behavior
Your code should just be :
if (authenticated)
{
bool isPersistent = whateverIwant;
FormsAuthentication.SetAuthCookie(userName, isPersistent );
Response.Redirect("successpage.aspx");
}
Do I have my web.config setup properly?
It should be ok for the domain attribute, as long as you want to share authentication among direct subdomains of mydomain.com (it won't work for x.y.mydomain.com), and mydomain.com is not in the public suffix list ( http://publicsuffix.org/list/ )
I would change the timeout and slidingExpiration attributes to :
<forms loginUrl="~/Default.aspx" timeout="525600" slidingExpiration="false" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
I guess it is a good way to handle the choice between one year persistent cookies and session cookies. See https://stackoverflow.com/a/3748723/1236044 for more info
I installed VM player in my machine and installed windows 2008 standard core inside. Also via command prompt added users and groups for a particular user as below,
creating user
dsadd user "cn=username,cn=users,dc=myname,dc=ca" -pwd password -disabled no
creating group
dsadd group "cn=groupname,cn=users,dc=myname,dc=ca"
Also added user to the existing group as below,
dsmod group "cn=groupname,cn=users,dc=myname,dc=ca" -addmbr "cn=username,cn=users,dc=myname,dc=ca"
Now i connect this users via my asp.net application in my local machine as below,
Web.config settings
<authentication mode="Forms">
<forms loginUrl="logon.aspx" name="adAuthCookie" timeout="10" path="/"/>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
script for authentication
void Login_Click(object sender, EventArgs e)
{
string adPath = "LDAP://domainaddress:389/DC=somename,DC=m"; //Path to your LDAP directory server
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
FormsAuthentication.SetAuthCookie(txtUsername.Text.Trim(), false);
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
---------
-------
}
where i am getting exception in string groups = adAuth.GetGroups(); as below
"Error authenticating. Error getting groups. The username is incorrect or bad password. "
Please let me know if i am doing some mistakes or please let me know how i find groups of assciated user.
Regards
Sangeetha