Persistent Cookie ( 4728 ) How to set .ASPXAUTH cookie's expires as session cookie? - session-cookies

I am having medium security issues with scanning software
[ Cookie Security: Persistent Cookie ( 4728 ) ]
Its seems that I used a persistent cookie.
I have found some answers tell to not set expiration ,but I am using System.Web.Security. Therefore I must set expiration as below ,or the class would be wrong. The FormsAuthenticationTicket.cs is a temp class there I could not edit the class.
Is there ways to set .ASPXAUTH cookie as session cookie ?
Not matter authTicket.expiration as 30 min or 1 hour the ASPXAUTH cookie's expiration still one day. How to make it work?
I set the IIS and made cookie's expriation as 30 mins, the cookie disappear at the right time, but on browser cookie's expriation still one day.
Here is my FormsAuthenticationTicket code:
Controllers:
ar authTicket = new FormsAuthenticationTicket(
version: 1,
name: _result.UserName,
issueDate: DTnow, DateTime
expiration:DTnow.AddHours(1),
isPersistent: false,
userData: _result.UserRank.ToString(),
cookiePath: FormsAuthentication.FormsCookiePath
);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket))
{
HttpOnly = true,
Secure = true
};
authCookie.Expires = DTnow.AddMinutes(30);
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
authCookie.Expires = DateTime.MinValue;
}
Response.Cookies.Add(authCookie);
Web.config:
<system.web>
<sessionState timeout="31"></sessionState>
<authentication mode="Forms">
<forms loginUrl="~/AccountUser/Login" />
</authentication>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<httpCookies httpOnlyCookies="true" requireSSL="true" /></system.web>
Global.asax:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User == null) return;
if (HttpContext.Current.User.Identity.IsAuthenticated == false) return;
if (Request.IsAuthenticated == false) return;
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket authTicket = id.Ticket;
string[] arrRolles = authTicket.UserData.Split(',');
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, arrRolles);
}
here is my IIS setting

I had found my answer. Here is my solution:
First, in Controller should not set "authCookie.Expires". I had set "authCookie.Expires = DateTime.MinValue" but that would be not work either !!
authCookie.Expires = DTnow.AddMinutes(30); ---delete it !
Second, in Controller the FormsAuthenticationTicket's attribute isPersistent should be false !
FormsAuthenticationTicket(
version: 1,
name: _result.UserName,
issueDate: DTnow, DateTime
expiration:DTnow.AddHours(1),
isPersistent: false,
userData: _result.UserRank.ToString(),
cookiePath: FormsAuthentication.FormsCookiePath
);
Third, check the Web.config setting ,the <forms ' attribute should not show cookieless
<forms cookieless="UseDeviceProfile" loginUrl="~/AccountUser/Login" name=".ASPXAUTH" requireSSL="false" slidingExpiration="false" timeout="30" />
should be:
<forms loginUrl="~/AccountUser/Login" name=".ASPXAUTH" slidingExpiration="false" timeout="30" />

Related

SlidingExpiration using authentication mode="None"?

I'm working with ASP.NET MVC application session, trying to implement ADFS authentication with OWIN using "UseCookieAuthentication" and "UseWsFederationAuthentication".
The ADFS authentication only works when I set authentication mode="None" in the web.config
The problem is that when I set authentication mode="None" and, for example, session timeout = 2 minutes, the session ends at 2 minutes after the login. Sliding expiration is not working and the user gets logged out even while using the site.
When I set authentication mode="Forms" the session behavies perfectlly and the user gets logged out only if 2 minutes passed after the last request, but the ADFS authentication stops working.
Does someone knows something about this problem?
The ADFS service is from an external partner, I don't know the configuration.
Here is my code:
<sessionState timeout="2" cookieName="MB_SEID"></sessionState>
<authentication mode="None">
<forms loginUrl="~/Home/Index" defaultUrl="/" path="/" name="UID" timeout="2" protection="All" slidingExpiration="true" enableCrossAppRedirects="true" />
</authentication>
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);
app.UseCookieAuthentication(new CookieAuthenticationOptions {
CookieManager = new SystemWebCookieManager(),
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes((double)sessionTimeout),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = CookieAuthenticationDefaults.CookiePrefix + DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnResponseSignIn = ctx =>
{
ctx.Options.ExpireTimeSpan = TimeSpan.FromMinutes((double)sessionTimeout);
ctx.Options.SlidingExpiration = true;
}
}
});
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
Wreply = replay,
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
UseTokenLifetime = false // set to false to manage session with the cookie middleware
});
}
My configuration was alright. The problem was an internal session management unknown by me.
Thank you all for your help.

MVC 4 - Cookie already expired on ActionExecutingContext

I'm a little lost on this and I can't find a solution.
I'm creating a Filter using below code:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionFilter :System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
And I'm validating if a cookie exist, is null or blank or expired with below code:
if (filterContext.HttpContext.Request.Cookies["MyCookie"] == null ||
String.IsNullOrEmpty(filterContext.HttpContext.Request.Cookies["MyCookie"].Value) ||
(filterContext.HttpContext.Request.Cookies["MyCookie"].Expires < DateTime.Now &&
filterContext.HttpContext.Request.Cookies["MyCookie"].Expires != new DateTime()))
{
But cookie is already expired in this section even when the value for expiration is set for one day after:
private void SetAuthenticationCookie(String username, String MyValue)
{
FormsAuthentication.SetAuthCookie(username.ToUpper(), false);
var cookie = FormsAuthentication.GetAuthCookie(username, false);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpCookie newCookie = new HttpCookie("MyCookie", MyValue);
newCookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(newCookie);
}
Here is the configuration on Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login/SignIn/" protection="All" timeout="1440" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />
</authentication>
Thank you so much again.

MVC external authentication with the [Authorize] attribute

A site authorizes through a separate system. Once the user is authorized, I want to store some additional information with their Auth cookie. I am able to do this using the code below.
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var serialized = JsonConvert.SerializeObject(accountNumber, Formatting.None, settings);
var authTicket = new FormsAuthenticationTicket(1, "MyAuthTicket", DateTime.Now, DateTime.Now.AddMinutes(15),
false, serialized);
var encTicket = FormsAuthentication.Encrypt(authTicket);
var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
HttpOnly = true,
};
Response.Cookies.Add(faCookie);
However, when I try to hit a WebAPI method marked with [Authorize], I get a 401 Unauthorized error. What am I missing?
The following needs added to web.config:
<system.web>
<authentication mode="Forms">
</authentication>
<!-- other stuff -->
<system.web>

Cross domain session asp mvc in IE and old browsers

Lets say that you have websites http://simple.com and a lot of subdomain, for example: http://first.simple.com, http://second.simple.com, http://last.simple.com.
Lets say that a user goes to last.simple.com and they get authenticated through the normal ASP .NET membership provider.
Then, from that site, they get sent to (redirection, linked, whatever works) site http://last.simple.com, and the intent of site http://first.simple.com was to pass that user to the other site as the status of isAuthenticated, so that the site http://last.simple.com does not ask for the credentials of said user again.
This worked in Chrome, Mozila, Opera(last versions), Safari, but don't worked in IE(all versions) and Opera( < v12.01).
Scheme:
User, address(first.simple.com) -> post query to server, json answer,
if auth - redirect. May be problem in json(need use 'jsonp')?
web.config
<system.web>
<authentication mode="Forms">
<forms name=".ASPXAUTH" protection="All" domain=".simple.com" enableCrossAppRedirects="true" />
</authentication>
</system.web>
SessionService
public void Authenticate(string username)
{
FormsAuthentication.SetAuthCookie(username, false);
var cookie = FormsAuthentication.GetAuthCookie(username, false);
cookie.HttpOnly = true;
cookie.Path = "/";
cookie.Domain = domain;
this.context.Response.AppendCookie(cookie);
}
Global.asax
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
const string aspSessionid = "ASP.NET_SessionId";
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
var cookie = Context.Request.Cookies[aspSessionid];
if (cookie != null && Context.Session != null && !string.IsNullOrEmpty(Session.SessionID))
{
Response.Cookies.Add(new HttpCookie(aspSessionid, Session.SessionID) { Domain = domain, Path = "/", Expires = DateTime.Now.AddDays(30) });
}
}
}

asp.net mvc authentication cookie issue

I'm trying to implement a "remember me" feature using ASP.NET MVC. It uses a customized authentication process as defined below.
Web.config:
<authentication mode="Forms">
<forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
</authentication>
Code to persist cookie:
public void SignIn(string userName, bool createPersistentCookie) {
int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
Code to retrieve cookie:
if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
}
The current code checks for Session for authentication. I'd like to add the ability to get the userName from cookie as well. I have 2 questions:
What do I need to do in order to retrieve the cookie?
How do I decrypt the cookie to obtain the userName?
To get the cookie:
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
Decrypt it with:
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

Resources