How to get recently authenticated user? - c#

I am working with MVC 3 and I have just implemented a wrapper for the FormsAuthenticationService.
Something similar to the following.
public void SignIn(string username, bool createPersistantCookie)
{
if (string.IsNullOrEmpty(username))
throw new ArgumentException("Value Cannot be null or empty", "username");
FormsAuthentication.SetAuthCookie(username, createPersistantCookie);
}
Reluctantly, I have gotten this to work, but now I am not quite sure how to get the information that I have stored.
Once the user is in my system, how can I now safely retrieve this information if I need to grab their UserID out of the database?

Based on the additional information provided, you want to store additional data with the FormsAuthentication ticket. To do so, you need first create a custom FormsAuthentication ticket:
Storing Data
Grab the current HttpContext (not worrying about testability)
var httpContext = HttpContext.Current;
Determine when the ticket should expire:
var expires = isPersistent
? DateTime.Now.Add(FormsAuthentication.Timeout)
: NoPersistenceExpiryDate; // NoPersistenceExpiryDate = DateTime.MinValue
Create a new FormsAuthentication ticket to hold your custom data.
var authenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
isPersistent,
"My Custom Data String"); //Limit to about 1200 bytes max
Create your HTTP cookie
new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket))
{
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain,
Secure = FormsAuthentication.RequireSSL,
Expires = expires,
HttpOnly = true
};
And finally add to the response
httpContext.Response.Cookies.Add(cookie);
Retrieving Data
Then you can retrieve your data on subsequent requests by parsing the stored authentication ticket...
Again, grab current HttpContext
var httpContext = HttpContext.Current
Check to see if the request has been authenticated (call in Application_AuthenticateRequest or OnAuthorize)
if (!httpContext.Request.IsAuthenticated)
return false;
Check to see if you have a FormsAuthentication ticket available and that it has not expired:
var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie == null)
return false;
Retrieve the FormsAuthentication ticket:
var authenticationTicket = FormsAuthentication.Decrypt(formsCookie.Value);
if (authenticationTicket.Expired)
return false;
And finally retrieve your data:
var data = authenticationTicket.UserData;

You haven't actually stored a user id in the database. All the code that you've written does is store an authentication cookie on the users computer, either as a session cookie (not persistent) or as a persistent one.
When your page refreshes, it will get the cookie automatically, decode it, and populate the IPrincipal object which you access from the User.Current property of your controller.

Related

manually check if claims token is ok

I have a custom attribute where I manually wanna check if a claims token is valid. How do I do that?
public class AuthorizeClaimsAttribute : AuthorizeAttribute {
protected override bool UserAuthorized(IPrincipal user) {
var cookie = HttpContext.Current.Request.Cookies.Get("bearerToken");
if (cookie != null) {
//Check if token is valid, how?
}
return false;
}
}
The token is created as follow:
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim("Username", model.Username));
identity.AddClaim(new Claim("IsAdmin", isAdmin.ToString()));
var properties = new AuthenticationProperties() {
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan)
};
var ticket = new AuthenticationTicket(identity, properties);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
Note: I cannot use the existing Authorize attribute. That´s why I need to check it manually.
One method is to store the token alongside its username somewhere in a persistant data structure
For example, when you create the Identity store the model.UserName & the accessToken in a a database of your choice.
Then, when you want to check your cookie you can re-open your database and query for it and take the appropriate action.
Also, adding that date in the database will also help you keep the size of it down resulting in faster searches, i.e. if your token only lasts for 3 months, delete the old ones as part of maintenance

Custom MVC Authentication without SetAuthCookie()

Because of the requirements of my project, I'm wanting to provide custom authenticate for my MVC controller actions. Therefore, I will not be using SetAuthCookie().
Intially I set a cookie as follows;
string userData = EncDec.MakeString(user.Email + "|" + user.UserId);
//the Cookie and FormsAuthenticationTicket expiration date/time is the same
DateTime cookieExpiry = DateTime.Now.AddMinutes(AccountPage.MvcApplication.COOKIE_EXPIRY_MINUTES);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
user.UserName, // authenticated username
DateTime.Now, // issueDate
cookieExpiry, // expiryDate
false, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
//create the cookie
HttpCookie cookie = new HttpCookie("ADV_" + Extensions.ControllerExtensionMethods.GetGuid(this), encryptedTicket);
cookie.Secure = true;
cookie.HttpOnly = true;
cookie.Expires = cookieExpiry;
Response.Cookies.Add(cookie);
The HttpCookie is being saved in the client browser with a encrypted FormsAuthenticationTicket.
Then within my controller actions, whenever I need to check and verify that the user is authenticated I call this method;
public static FormsAuthenticationTicket IsAuthenticated(string guid)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["ADV_" + guid];
if (cookie != null)
{
string encryptedTicket = cookie.Value;
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedTicket);
if (!ticket.Expired)
{
//if the user is authenticated and the cookie hasn't expired we increase the expiry of the cookie - keep alive
DateTime cookieExpiry = DateTime.Now.AddMinutes(AccountPage.MvcApplication.COOKIE_EXPIRY_MINUTES);
//create a new ticket based on the existing one
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
ticket.Version, // ticket version
ticket.Name, // authenticated username
ticket.IssueDate, // issueDate
cookieExpiry, // expiryDate, changed to keep alive if user is navigating around site
false, // true to persist across browser sessions
ticket.UserData, // can be used to store additional user data
ticket.CookiePath); // the path for the cookie
string newEncryptedTicket = FormsAuthentication.Encrypt(newTicket);
//keep alive
HttpCookie newCookie = new HttpCookie("ADV_" + guid, newEncryptedTicket);
newCookie.Secure = true;
newCookie.HttpOnly = true;
newCookie.Expires = cookieExpiry;
HttpContext.Current.Response.Cookies.Set(newCookie);
return newTicket;
}
}
return null;
}
Every time the user is re-authenticated, I am increasing the time out of when the cookie will expire, so that the login is keep alive.
Everything seems to work fine, and the users are correctly authenticated, and if they aren't authenticated I redirect them to a login page, and they can't access methods if they aren't authenticated either.
My questions are:
Is this way of dealing with the authentication secure.
Is there anything I should be aware of, in terms of a security risk.
Thanks.
You basically need to look at creating a Custom Authentication Attribute.
I'm not going to provide the actual implementation here, but this will put you on the right path.
Here's the basic representation :-
public class GoogleAuthAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
IIdentity ident = filterContext.Principal.Identity;
if (!ident.IsAuthenticated || !ident.Name.EndsWith("#google.com"))
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "GoogleAccount"},
{"action", "Login"},
{"returnUrl", filterContext.HttpContext.Request.RawUrl}
});
}
}
}
I've took this from the Apress Book i'm currently reading on MVC5. If OnAuthentification fails, you set the Result property of the AuthenticationContext, this is then passed to the AuthenticationChallengeContext, where you can add your challenge code.
In my example, the user is redirected to the login page.
All you need t do, is place this AuthentificationAttribute on the Action Methods you require.
You should be able to build in or work your custome security code in to this.
You should really ask yourself if its a good idea to be adding custom security measures, as it can lead to more problems that you want.

Is it possible to update the current IPrincipal without creating a new connection in SignalR 2.0.x?

We use custom forms authentication in MVC4. We create a FormsAuthenticationTicket with custom data (another authentication ticket for a backend sub system) and store it in a cookie. This cookie is read and dectypted in the FormsAuthentication_OnAuthenticate method in global.asax. From the decrypted data we create a custom IPrincipal object that we set as the current User.
We also use a sliding expiration scheme for the ticket and if it's about to expire we create a new ticket and update the cookie and create a new custom IPricipal object.
We have set ut SignalR to ping the server regularly, and the ticket is correctly renenewd.
The problem is that the updated IPrincipal is never propagated to SignalR (it's only set the first time). Is this even possible or do we need to create a new connection when the ticket is renewed?
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var ticketManager = DependencyResolver.GetService(typeof(ITicketManager)) as ITicketManager;
var ticket = ticketManager.DecryptAndValidateTicket(authCookie.Value);
var newTicket = ticketManager.RefreshTicketIfNeeded(ticket);
if (newTicket != null) {
var cookie = ticketManager.CreateCookie(newTicket);
e.Context.Response.Cookies.Add(cookie);
ticket = newTicket;
}
var user = ticketManager.Authenticate(ticket);
Thread.CurrentPrincipal = user;
HttpContext.Current.User = user;
e.User = user;
}
You need to create a new connection if you want to update the current IPrincipal of a SignalR connection.
The reason is pretty straightforward: SignalR requests can last indefinitely.
Cookies are sent and authentication/authorization occurs at the beginning of a request. This is also when the IPrincipal is set. In SignalR at least, the IPrincipal is stored on the request itself.
I suppose it might be possible to update the IPrincipal if you had references to the active SignalR requests for the given user, but I think your best bet is establishing a new SignalR connection if the IPrincipal changes.

Principal get lost after one request

I have the function AffiliateLogin in a controller that sets the Principal.
the row principal.User = user; is actually the one storing the Principal.
But after I redirect to another controller, and test my AuthorizeWithRolesAttribute attribute, the principal is reset.
This is one second after the login, you can see the red arrow:
this is the function that stores it.
What am I doing wrong?
Thanks
public JsonResult AffiliateLogin(string email, string password)
{
if (ModelState.IsValid)
{
Affiliate user = api.GetUserByCredencials<Affiliate>(email, password);
if (user != null)
{
IIdentity identity = new UserIdentity(true,user.Email);
UserPrincipal principal = new UserPrincipal(identity, new string[] {"Affiliate"});
principal.User = user;
HttpContext.User = principal;
return Json("Login success");
}
}
return Json("Fail To Login");
}
The principal property won't survive between web requests. You had to set it again in the next request after redirection.
If your doing doing custom authentication/forms authentication you should call
FormsAuthentication.SetAuthCookie
The next http from the browser with that cookie , Asp.net will process the cookie and set
the current claims principal. So you can check
var principal = ClaimsPrincipal.Current; //normally this reverts to Thread.CurrentPrincipal,
Here is a good place to learn a bit more
http://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal.current

Membership provider class

I want to know how I can implement membership provider class to have ability to remember users who signed in.
I have Membership provider class and I need functionality of "Remember Me" checkbox but I don't know how I can implement some methods
In order to implement this functionality you must create a persistent cookie with some expiration date on the users computer. So if the user checks the Remember me checkbox you issue the following cookie:
var cookie = new HttpCookie("_some_cookie_name_", "username")
{
Expires = DateTime.Now.AddDays(15) // Remember user for 15 days
};
Response.Cookies.Add(cookie);
And then upon showing the login screen you could check if the cookie is present and prefill the username:
var cookie = Request.Cookies["_some_cookie_name_"];
if (cookie != null)
{
usernameTextBox.Text = cookie.Value;
}
I would use a Hashtable if it's in C#, keyed by the user id. Something like this (where lsdfjk is just whatever string the user ID corresponds to, and assuming that there is a class UserInfo defined, with a constructor taking string userID as an argument):
string userID = "lsdfjk";
UserInfo userInfo = null;
Hashtable htMembers = new Hashtable();
if (htMembers.ContainsKey(userID))
{
userInfo = (UserInfo)htMembers[userID];
}
else
{
//It's a new member
userInfo = new UserInfo(userID);
}
"Remember Me" doesn't have anything to do with a Membership Provider really. Basically it is just a function of Forms Authentication, where you set a persistent cookie so that when people show up at the website, it can log them in automatically.
You can do this automatically using the RedirectFromLoginPage() method.
FormsAuthentication.RedirectFromLoginPage(username, true);
The second parameter, "true", means "set a persistent cookie". The user will be logged in until the cookie expires or they clear their cookies.
If you need more control over it, you can manually set a cookie by manipulating the cookies collection directly.

Categories