HowTo use Session in ASP.NET with custom session key parameter - asp.net-mvc

Is it possible to use ASP.NETs session state with URL like
http://myserver/somesite?sessionKey=thekey
The problem is, that I have to write a site for a client software which authenticates a user by a request like
http://myserver/somesite?user=xyz&passwd=xyz
The client expects than to get a session key as result if the authentication was successful.
This session key will then be used as variable in the query as shown above. The client does not support cookies.
How can I implement this behavior by using ASP.NET MVC 4?
P.S.: I know it is absolutly not the way to go but I am not in position to change the client.

If I do understand you correctly, you could just try it, right?
(We already met it, and it was a pain for searching engines)
<sessionState mode="InProc" timeout="5" cookieless="true" />
And I can say it is working
The url generated instead of
"http://server/Product/en-GB/MyEntity"
is now:
"http://server/Product/(S(rxavnpuw05o3fmy3tjnuystr))/en-GB/MyEntity"

Related

Mvc4 set user as logged in when user info is found in the session

I am working on a new mvc4 site,and am using mvc4 forms authentication.
the users of the site expect to be able to login to the companies main site and click on a link and go to this new site i am developing. the old site stores the logged in user in a session variable. is it possible for me to check if the session variable exists and log the user in to my forms authentication? or will they need to login again?
Make the same machineKey section in your web.config in system.web like this:
<system.web>
<machineKey validationKey="SAME_KEY_GOES_HERE" ... />
...
You can generate machineKey here.
Then your goal is to pass all the authentication cookies from one website to another. I think you can store them in database, and provide authenticated users with an unique link to your new website. New website can read the key from database, and set cookie values obtained from the existing website. After that, user will be authenticated on your new website.
Update:
There could be easier and little bit less secure way of doing this. Don't keep cookie data in database, just create a form on the first website with post action. This form must contain all authentication cookies in hidden values. Action of the form must point to your second website. On the second website, you just need to place submitted form values to cookies. That's it! Much easier! (yep, and you need same machine key)

MVC3 mixed forms and Windows authentication

I currently have an intranet site that is accessed by external customers. I therefore set this up using Forms Authentication. However the powers that be (my bosses) want all our domain users to not have to enter their username and password to access the site.
I've done a bit or reading and everything seems to point to setting up a WinLogin.aspx page that you alter to use WindowAuthenthication and then redirect from there.
I have a problem with this as I don't like the idea of putting an aspx form in my mvc application.
Can anyone tell me how to achieve mixed authentication using a strictly MVC Controller/Action setup without a second application?
NOTES: running MVC 3 on an IIS 7 box.
Forms Authentication is not related to the URL or physical structure of your files. What matters is that a URL should ultimately map to a physical (or virtual) resource on the server, and be processed, and be returned back to the user.
Thus, somewhere in between for each incoming call (each HTTP request, even those for CSS and JavaScript files), you have to see if the current user has enough permission to access it or not. If no, then you might redirect him to the login page.
If you want, you can have a URL like /user/windowslogin where user is the name of the controller, and windowslogin is the name of your action method. Then you can create a custom authentication attribute (something like [WindowsAuthentication]) on your windowslogin action, and in that attribute (which is an MVC filter in essence), you can see if the current request comes from within your domain, and if so, talk to Active Directory for authentication or stuff like that, and on case of successful authentication, create an authentication cookie using FormsAuthentication class, and the rest of the story.
However, I don't think this would be an easy task. Others might introduce better solutions.

MVC: logged in, but no session vars?

I use chrome as debugging browser.
When I start my MVC (Razor) website, click the stop button and the website keeps running in chrome ,while I can make changes in VS ... perfect.
But sometimes (due to I don't know what changes), when I refresh a page, I'm still logged in, but I looses all my session vars.
How can I catch if session vars is cleared, so I can take my users back to login page? (I need a kinde global.asax page_request method.
I do have the .. <forms loginUrl="~/Account/LogOn" timeout="2880" /> ... but Im not logged out - only session vars are cleared.
It's because your login state is persisted in a client cookie. The session state is persisted on the server in memory (or whatever). When your app restarts the session is cleared but the user still has a valid forms authentication token (assuming forms authentication here) on their machine. Forms authentication does't use session in any way by default.
So, at the beginning of the request, you can either reload the user session from the database when it's null (I think this is the preferred approach if possible) or redirect the user to the login screen with a message saying "ooops, sorry we've lost your session" (which is not good!)
If you use the built-in Authorization functionality, you can just add the [Authorize] attribute. There's some info on using custom authentication here:
ASP.NET MVC Authorization
Lee Gunn explained it well. One solution would be to create a custom filter attribute similar to Authorize that verifies the session has the values you're expecting and decorate the appropriate controllers/actions.

Session vs Cookie vs Custom IPrincipal

I'm working on a project where certain logged in users have a dedicated page which they can choose the url of. When a user logins in i would like to display a link "View my page". I was just wondering what is the best way to store this baring in mind it needs to be accessible for as long as the user is logged in (The site has a remember me feature as well). Would a session variable surfice? or a cookie? Or a custom IPrincipal?
Many thanks
Matt
UPDATE:
What do you guys thing of using the UserData string you can store with the authentication cookie? It seems to satisfy my requirements, but i can't say I know a lot about it.
Forms authentication (based on cookie) should be enough. Here you can read about using FormsAuthentication with custom IPrincipal:
ASP.NET 2.0 Forms authentication - Keeping it customized yet simple
This page is about how forms authentication works:
Explained: Forms Authentication in ASP.NET 2.0
When you use forms authentication, you have Authorize attribute to limit access to controllers and action. It works pretty well. Your own IPrincipal is not necessary. I wouldn't use Session, because it can be easily lost.
Thanks guys, however I have ended up using the UserData string that you can store along with the authentication cookie. This way I know the data will always be available while the user is authenticated. And since I only need to remember simple data (the users url), this seems like a good solution.
Anybody with the same problem can find more info here:
http://www.asp.net/learn/security/tutorial-03-cs.aspx (See step 4)
If what you mean is that you want to display a different custom URL for each user and you simply want to cache that URL then there's a few things to consider:
If you use a session value or a cookie then you need code for the possibility of the value not being present. Both the server session or the browser session could expire and the user could still be logged in.
If you use a cookie you could consider setting the cookie expiry to the same as the authentication cookie expiry but this still doesn't guarantee availability.
A cookie value will not be secure, it could be modified. A session value will be secure.
If you're using custom forms authentication then you could store the URL in the authentication cookie itself and then load it into a custom IPrincipal. I would advise against that as I don't feel it's the right place.
If you're just trying to cache the URL then as long as your code re-fetches the data when the value is not present then a session value or a cookie will be fine depending on the level of security required.
If I have read that wrong and you just want to show/hide a link to depending on whether a user is authorized or not you can simple use
<% if (User.Identity.IsAuthenticated) { %>
view my page
<% } %>
And have your MyPage action in your controller render the dedicated page for the user.

RememberMe with DotNetOpenId in ASP.NET MVC

Using DotNetOpenAuth 3 in ASP.NET MVC and implementing a RememberMe facility ...
I'm finding that even if I set createPersistentCookie to true in FormsAuthentication.RedirectFromLoginPage and FormsAuthentication.SetAuthCookie the user is not remembered once the ASP.NET session times out.
If I inspect the cookie I find it is marked as persistent and does have an expiry date way in the future, I assume because I set my web.config FORMS timeout to a few years away. Anyhow, if the user closes the browser and re-opens it they are remembered correctly - as long as the ASP session hasn't timed out.
An older post of Scott Hanselmann's makes me wonder if it is because FormsAuthentication tries to renew the authentication ticket and maybe in an OpenId model that doesn't work but I have set FORMS SlidingExpiration="false" in web.config and anyway I thought that forcing a persistent cookie would make that stuff irrelevant.
I'm also wondering why the DotNetOpenId MVC sample doesn't include a RememberMe checkbox - maybe there's something tricky about it?
On the other hand, here at StackOverflow I see I am automatically remembered across sessions. Wondering whether they used something other than DotNetOpenId to do their OpenId authentication.
Anybody else done RememberMe successfully with DotNetOpenId in ASP.NET MVC? Any tricks?
[Update]
Thanks for trying to help, Andrew. Turns out this was not about DotNetOpenId.
I gather, after reading this, that my hosting provider is probably recycling the app pool regularly and that's causing the authentication ticket encryption to be done with a new machine key.
As per the preceding linked article I added the following under System.Web in my Web.Config and it resolved the issue:
<machineKey
validationKey="(generated a new key to place here)"
decryptionKey="(generated a new key to place here)"
validation="SHA1"
decryption="AES" />
I still think the cookie name should match... but here's something else.
It sounds like you're saying as long as your timeout in the web.config file is large, then things work. But that once you shorten it, your persistent cookie doesn't outlast the timeout value. This forum topic helped answer this for me:
http://forums.asp.net/p/1010241/1347970.aspx#1347970
It seems that the timeout in web.config affects all cookies. It says how long the authentication ticket lasts. All auth cookies have this 'time to live' timeout whether they are 'persistent' or not. So the difference between persistent cookies and non-persistent cookies are that the former will last across different browser sessions and the latter will die (early) if the browser is closed.
Does that make sense?
Does the cookie name match in your web.config file and your controller's call to FormsAuthentication.SetAuthCookie? This may be a bug in the DNOI sample, but I suspect if you have a cookie name in your web.config file (as the DNOI sample does), then you probably have to set the cookie name as the third parameter to SetAuthCookie or RedirectFromLoginPage. Otherwise, forms auth doesn't recognize the persistent cookie you set as the login cookie.

Resources