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>
Related
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" />
asp.net mvc project when publish, it always lose session after 15-20 minutes.
my global.asax
enter code protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
Login Method :
//clear any other tickets that are already in the response
Response.Cookies.Clear();
//set the new expiry date - to thirty days from now
DateTime expiryDate = DateTime.Now.AddDays(30);
//create a new forms auth ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, login.EmailID, DateTime.Now, expiryDate, true, "Kullanici Bilgisi");
//encrypt the ticket
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
//create a new authentication cookie - and set its expiration date
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
authenticationCookie.HttpOnly = true;
//add the cookie to the response.
Response.Cookies.Add(authenticationCookie);
Please help me. Im control on google developer tools. I see timeout 2018 but session is always losing redirect to login page.
Web Config:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/user/login" slidingExpiration="true"></forms>
</authentication>
I am having an issue where users of my website login sessions are expiring way before it should.
Here is my login method”
public ActionResult Login(LoginModel model, string returnUrl)
{
var mcookie = new MyCompanyCookie();
if (ModelState.IsValid)
{
using (var myRepo = new MyCompanyRepositry())
{
var passwordHash = MyCompany.Web.Portal.Helpers.Security.CreatePasswordHash(model.Password);
var userAccount = myRepo.GetMyCompanyUser(model.UserName,model.PartnerAccessCode);
if(userAccount != null && userAccount.Password == passwordHash && userAccount.PartnerAccessCode == model.PartnerAccessCode.ToUpper())
{
mcookie.GetMMformsauthentication(userAccount, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name,access code or password provided is incorrect.");
}
}
And forms authentication ticket:
public void GetMMformsauthentication(UserAccount useraccount, bool createPersistentCookie)
{
const string UnknownUsername = "anonymous";
// Composing UserData to be stored in the auth cookie
var userCookieData = new MarvMentUserCookieData()
{
UserId = useraccount.UserID,
Password = useraccount.Password,
PartnerAccessCode = useraccount.PartnerAccessCode
};
var ticket = new FormsAuthenticationTicket(1, string.IsNullOrEmpty(useraccount.UserID) ? UnknownUsername : useraccount.UserID, DateTime.Now,
DateTime.Now.AddDays(100), createPersistentCookie, userCookieData.ToString(), FormsAuthentication.FormsCookiePath);
var hashedCookie = FormsAuthentication.Encrypt(ticket);
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedCookie); // Hashed ticket
authCookie.HttpOnly = true;
authCookie.Expires = ticket.Expiration;
authCookie.Path = ticket.CookiePath;
authCookie.Secure = false;
HttpContext.Current.Response.SetCookie(authCookie);
}
}
And expiration settings inmy Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Here you can see that the forms expiration settings is set 2880 minutes however users are beign logged out after around 5-10 minutes.
The cookie is set to expire in 100 days
Does anyone have and idea what may be causing this issue?
It looks issue is not with session in authentication tag. Just check what happens if cookies stuff is commented... If Session retained for more time, then focus on cookie stuff.
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) });
}
}
}
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