Authentication does not save cookie - asp.net

I have a login form where I should save into cookie the authentication in case the user close and reopen the browser.
I tried with
<authentication mode="Forms" />
With this code, I save the cookie into login
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(Login1.UserName, True, 600)
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
and here I read the cookie
Dim FormsAuthCookie As HttpCookie = Request.Cookies(FormsAuthentication.FormsCookieName)
Dim usr As String = FormsAuthCookie.Value
Dim Ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(FormsAuthCookie.Value)
usr = Ticket.Name & ""
The FormsAuthookie.value is always NULL, cannot understand what is wrong

Related

Asp.net Forms Authentication with Token and RefreshToken problem

I'm using WebForms with forms authentication. I'm connecting my application with an rest api token mechanism.
My problem is that I want to ask for my new access token using my refreshtoken.
I currently do this job in Global.asax Application_AuthenticateRequest method.
When I obtain the accesstoken i update the ticket but i am redirected to the login page.
I've try to use Response.Redirect and i am redirected to the original url but i lost the state of the page. It's as if I has reloaded the page. Somebody know what i'm doing wrong?
Below is my global.asax code in VB.net:
Thanks!
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
Try
If Request.Cookies(FormsAuthentication.FormsCookieName) IsNot Nothing Then
Dim authCookie As HttpCookie = (Request.Cookies(FormsAuthentication.FormsCookieName))
If Not String.IsNullOrEmpty(authCookie.Value) Then
Dim ticket = FormsAuthentication.Decrypt(authCookie.Value)
If ticket.Expired Then
'reauth cookie Is My refreshtoken
If Request.Cookies("reAuthCookie") IsNot Nothing Then
Dim funciones As New Funciones.Usuarios
Dim reAuthCookie As HttpCookie = Request.Cookies("reAuthCookie")
If Not String.IsNullOrEmpty(reAuthCookie.Value) Then
Dim refreshToken As String = reAuthCookie.Value(0).ToString
Dim login As Entidades.Login = funciones.renovarAccessToken(refreshToken)
Dim ticketExpiration As Date
ticketExpiration = Date.Now.AddSeconds(CDbl(login.Expires_in) - 20)
Dim userData As String = Newtonsoft.Json.JsonConvert.SerializeObject(login)
ticket = New FormsAuthenticationTicket(1, login.Username, DateTime.Now,
ticketExpiration, True,
userData, FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
Response.Cookies.Remove("reAuthCookie")
reAuthCookie.Expires = Now.AddMonths(2)
reAuthCookie.Path = "/"
reAuthCookie.Value = login.Refresh_token
Response.Cookies.Add(reAuthCookie)
End If
End If
End If
End If
Else
If Request.Cookies("reAuthCookie") IsNot Nothing Then
Dim funciones As New Funciones.Usuarios
Dim reAuthCookie As HttpCookie = Request.Cookies("reAuthCookie")
If Not String.IsNullOrEmpty(reAuthCookie.Value) Then
Dim refreshToken As String = reAuthCookie.Value.ToString
Dim login As Entidades.Login = funciones.renovarAccessToken(refreshToken)
Dim ticketExpiration As Date
ticketExpiration = Date.Now.AddSeconds(CDbl(login.Expires_in) - 20)
Dim userData As String = Newtonsoft.Json.JsonConvert.SerializeObject(login)
Dim ticket = New FormsAuthenticationTicket(1, login.Username, DateTime.Now,
ticketExpiration, True,
userData, FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
Response.Cookies.Remove("reAuthCookie")
reAuthCookie.Expires = Now.AddMonths(2)
reAuthCookie.Path = "/"
reAuthCookie.Value = login.Refresh_token
Response.Cookies.Add(reAuthCookie)
End If
End If
End If
Catch ex As Exception
Throw ex
End Try
End Sub

Manually remove Auth Cookie from .Net MVC Application

One of my recent .Net MVC based web application i have a situation by which i need to use multiple auth cookie like
1 Forms Auth Cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(30), RememberMe, 'data1', FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
HttpContext.Current.Response.Cookies.Add(cookie);
2 Custom Auth Cookie
FormsAuthenticationTicket cstTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddDays(30), isPersistent, 'data 2', FormsAuthentication.FormsCookiePath);
string _encryptedTicket = FormsAuthentication.Encrypt(cstTicket);
HttpCookie cstCookie = new HttpCookie("iCstm", _encryptedTicket);
HttpContext.Current.Response.Cookies.Add(cstCookie);
I need to remove both the cookie when someone logout from the application. If i call FormsAuthentication.SignOut(); then it remove basic auth cookie. I tried to remove second cookie by setting Expires value like
HttpContext.Current.Request.Cookies["iCstm"].Expires = DateTime.UtcNow.AddYears(-1);
HttpContext.Current.Response.Cookies["iCstm"].Value = "";
HttpContext.Current.Response.Cookies.Add(HttpContext.Current.Request.Cookies["iCstm"]);
But this will not work in case of auth cookie. Is there ny way to handle this issue.
Thanks in advance.

Authenticating user with second login

asp.net I am using a second login control to verify a users email. They will get an Email that directs them to a confirm login window. Not the login that is used in the web.config file. So. I assumed that when they entered the loggedin event the would be authenticated, but it seems they are not. All I want to do here is set the profile property 'confirmed' = Y. So I added code:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox userName = (TextBox)Login1.FindControl("UserName");
string uname = userName.Text;
TextBox Password = (TextBox)Login1.FindControl("Password");
if (Membership.ValidateUser(userName.Text, Password.Text) == true)
{
BDrider bd = new BDrider();
string UserData = bd.getRidFromUsername(uname).ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
}
}
But on the IsAuthenticated line it returns false ???
Seems that you are creating the cookie and trying to "consume it" in the very same request. Unfortunately, this won't work. The forms authentication module will pick up the cookie and maintain the session starting from just the next request.
A possible workaround would be to redirect to an auxiliary page and perform your operation there and then redirect to Main.aspx. Your code would be then
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect( "Auxiliary.aspx" );
and in the Auxiliary.aspx:
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
However, I don't quite get the if. If you are just issuing the forms cookie, the user surely is authenticated. Why it would be otherwise?

Forms Authentication Cookie Not Persisting on Server But does on LocalHost

I have been working on a web application that is setup on IIS 7 as one of several applications and web services operating under the DefaultWebSite. When developing on localhost, my FormsAuthentication cookie persists; however, when published on the server the cookie(s) are not persistent. I am using SQLServer sessions, and have validation keys in the web config to rule out application pool recycling. I have been trying to figure this out for a while now with no luck...please help!
Here is some code below:
<forms name=".OPTFORMSTEST" loginUrl="~/Secure/Login.aspx" defaultUrl="~/Default.aspx" timeout="240" path="/" slidingExpiration="false" protection="All" />
Public Shared Function DoLogin(ByVal strUsername As String, ByVal isPersistent As Boolean)
Dim authTicket As FormsAuthenticationTicket
Dim authCookie As HttpCookie
Dim strUserData As String = strUsername
Dim intTimeoutPersist As Integer = 43200 '(30 days)
Dim intTimeoutNonPersist As Integer = 300 '(5 hours)
Dim intRtn As Integer = 1
Dim strCookiePath As String = Current.Request.Url.AbsolutePath.Remove(Current.Request.ApplicationPath.Length)
Try
'set cookie timout period and create auth ticket based on isPersistent
If isPersistent Then
'create a persistent ticket
authTicket = New FormsAuthenticationTicket(1, strUsername, _
DateTime.Now(), _
DateTime.Now.AddMinutes(intTimeoutPersist), _
True, strUserData)
Else
'create a temp ticket
authTicket = New FormsAuthenticationTicket(1, strUsername, _
DateTime.Now(), _
DateTime.Now.AddMinutes(intTimeoutNonPersist), _
False, strUserData)
End If
'create encrypted string for user data
Dim strEncr As String = FormsAuthentication.Encrypt(authTicket)
'create cookie
authCookie = New HttpCookie("OPTFORMSTEST", strEncr)
'set cookie expiration based on the auth ticket
If isPersistent Then
authCookie.Expires = authTicket.Expiration
End If
Current.Response.Cookies.Add(authCookie)
Catch ex As Exception
intRtn = -1
End Try
Return intRtn
End Function
After some experimenting, I found out that the RedirectFromLoginPage method was creating another cookie when used from the production box. I replaced with a Response.Redirect and only one cookie was created and it was persistent.

User.Identity.IsAuthenticated is false after adding auth cookie

I have the following code to add authentication cookie to the response and redirect to homepage
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But in the Home.aspx, User.Identity.IsAuthenticated is still false. why?
Finally got it working. Here is it in nutshell
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
I followed the code sample from this MSDN page:
You don't have to add the cookie to the response yourself.
You were doing this:
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But instead of doing a GetAuthCookie and then adding it, you can just use SetAuthCookie:
HttpCookie authCookie = FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("~/Home/Home.aspx");
When you look at the MSDN page for SetAuthCookie, you see that it not only adds the cookie to the Response (or the URL), but it also creates and encrypts a ticket:
Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.
That's probably why it doesn't work when you just try to add the cookie yourself.

Resources