Getting the logged in username in ASP.NET MVC3 intranet application - asp.net-mvc-3

I am working on a MVC 3 intranet application ( windows authentication ). The application must display the profile page of the user once a user logs in. In order to do that the username of the logged in user must be passed in as a route parameter in the following route in Global.asax.cs.
routes.MapRoute(
"Initial",
"{controller}/{action}/{emailAlias}", // URL with parameters
new { controller = "Home", action = "Home", userId = **<USERNAME>**}
);
Here, for the I've used some alternatives.
At first I used Environment.Username. Which works well in development. But not after publishing. Because then Environment.Username yields the name of the applications pool which the app runs in. As described here.
Controller.User.Identity.Name is used to get the desired username in controllers, works well in pre and post publishing. But it cannot be used in the context of Global.asax.cs.
System.Web.HttpContext.Current.User.Identity.Name yields null reference.
System.Security.Principal.WindowsIdentity.GetCurrent().Name works kind of same as Environment.Username
I'm sure it's easy to figure out that I'm a noob by now. Maybe I've missed something obvious. If so please point that out or please tell me of a simple solution thanks in advance.

The global.asax code is supposed to be run at application startup (and shutdown) and you don't have any session or a user at that time (hence the name global). Why do you need the username in the route? You should just use User.Identity.Name in the controllers' code to identify the user instead of relying in getting it as a parameter.

Related

eXist persistentlogin is not persisting

In eXist 4.7 I implemented the persistentlogin in my controller.xql and I have noticed that it does not "persist" very long in my eXist web app ("thema"), whereas the eXide web app in the same eXist instance, using the same login function, persists authenticated status as expected.
Specifically, if I am logged in to both in the evening, the next morning eXide is still logged in (ie. authenticated = true), and my app is not.
I implemented it as follows, with duration set at 30 days ("P30D"):
import module namespace login="http://exist-db.org/xquery/login" at "resource:org/exist/xquery/modules/persistentlogin/login.xql";
let $duration := request:set-attribute("duration", "P30D")
let $set-user := login:set-user("org.exist.thema", (), false())
So I've further tested the persistence in my web app and I find that the login "disappears" (loses authentication?) after about an hour of being non-active on the site.
Is there some other eXist setting I've missed in configuring this?
The only documentation I've been able to find on this is in the notes in the code of login.xql: https://github.com/eXist-db/exist/blob/develop/extensions/modules/persistentlogin/src/main/resources/org/exist/xquery/modules/persistentlogin/login.xql
According to the source code for the login module, there are two ways to designate the duration for the login session:
Via the $maxAge parameter of the login:set-user function
Via a duration request parameter (which overrides the $maxAge parameter when present)
In your code, you are setting a duration request attribute, not a request parameter; for more on the difference, see this answer. This explains why the login module is completely ignoring your attempts to declare a duration.
To fix your problem, you could either (1) change to the first method:
login:set-user("org.exist.thema", xs:dayTimeDuration("P30D"), false())
... or (2) submit the request parameter in your login form, as eXide does in its login form; see https://github.com/eXist-db/eXide/blob/master/index.html.tmpl#L505-L528.

Where to check if an User is logged in in a Laravel Application?

I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.

Laravel 5.1 use session to restrict direct access using urls users based on user role

I have 2 laravel projects, 1 for the front end where i m using html css angularjs. The second for api controllers. I call using http post and get the api controllers functions using angularjs to get content data.
In the front end i have a menu this menu appears differently based on user role, if admin or no.
This is done. My problem is the access for views using the url in the browser.
So I have a query where I get for each user what modules in the menu can he see. Now I'm putting the result in Laravel session.
$menu = DB::select menu by user id ... //Getting menu query based on user if admin or no
session(["menu" => $menu);
return session('menu');
I'm getting the results and the menu is showing good in the website based on the logged user if he s admin or no.
Now, to solve the direct url access issue, I want to use this session and compare the url to this session, if the url exists in the session i will let him access, if no i will redirect him to somewhere.
any idea?
I would strongly suggest looking at the Laravel documentation on Authorization before going too far down a custom implementation:
https://laravel.com/docs/5.1/authorization
Without knowing more about how your front-end and back-end applications interact with each other, it is a little difficult to get into speciifics but i shall do my best.
Each page returned by Laravel has access to a Request object which contains information about the request which returned the page. You can access this Request and its assocaited Route using Laravels helper functions (if you are not passing it to the view already). The getPrefix() method will return the root relative url which you can then use as you see fit. For example:
// Return and store the URL as a string
$url = request()->route()->getPrefix();
// Check your session for the URL/s you want to allow and compare to the stored URL
if (session()->get('URL') == $url) {
// User is allowed access to the page
// Do something ...
} else {
// User is not allowed access to this page
// Redirect back or to a route of your choice
return redirect()->back();
}
I hope this gives you some ideas, good luck!

ASP.NET MVC2 Empty Project Not Loading

My environment consists of Visual Studio 2010 and Windows 7 a few months ago I developed an MVC2 application with no problems however after trying to create a new project recently I received the error below.
I did find the link http://support.microsoft.com/kb/894670 but this is not relevant because I am not using IIS for testing, just F5 to get this working :)
Any ideas or help would be appreciated.
Server Error in '/' Application.
--------------------------------------------------------------------------------
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4927
The Empty MVC 2 template application does not define any controllers or views. When you create a new Empty MVC 2 application and immediately run it, you will see the error message you posted.
If you check the Global.asax file, you'll see that the project template automatically registers a default route specifying a default controller named "Home" and a default action named "Index".
To get this to run, right-click on the Controllers folder, then choose Add->Controller... Name the controller "HomeController". You can leave the check box to "Add action methods for Create, Update, Delete..." unchecked.
In the HomeController.cs file, right click in the Index() method and choose Add View...
Leave the View name as "Index", uncheck "Select master page", and then click Add.
In the Index view, you can enter some HTML and run the project; you should now see the page rendered by Index.aspx.
One thing I am not sure of is why your error message lists the .NET Framework version as 2.0. If you still have problems, check the target framework on your project properties.
Make sure that the routes are set properly and that you have default values for a controller and action. For example if you have the following route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
Make sure that you have a HomeController with an Index action.

Manually start session with specific id / transitioning session cookie between domains

My host requires me to use a different domain for SSL secured access (shared SSL), so I need to transition the user session between two domains. One part of the page lives at http://example.com, while the SSL'd part is at https://example.hosting.com. As such I can't set a domain-spanning cookie.
What I'm trying to do is to transition the session id over and re-set the cookie like this:
http://example.com/normal/page, user clicks link to secure area and goes to:
http://example.com/secure/page, which causes a redirect to:
https://example.hosting.com/secure/page?sess=ikub..., which resurrects the session and sets a new cookie valid for the domain, then redirects to:
https://example.hosting.com/secure/page
This works up to the point where the session should be resurrected. I'm doing:
function beforeFilter() {
...
$this->Session->id($_GET['sess']);
$this->Session->activate();
...
}
As far as I can tell this should start the session with the given ID. It actually generates a new session ID though and this session is empty, the data is not restored.
This is on CakePHP 1.2.4. Do I need to do something else, or is there a better way to do what I'm trying to do?
When Configure::write('Security.level') is set to medium or higher, session.referer_check is implicitly activated, which makes the whole thing fail. Setting the security level to low (or using a custom session configuration) makes everything work as it should.
There went about 5 hours of debugging... ( -_-;;)
My first thought is to use the Cake file sessions and copy the file over, and then perhaps try and start a new session with that phpsessid, although I'm not even sure if that would actually work or not :)
With Cake 2.6.1 -- This is what worked for me.
$this->Session->id("tfvjv43hjmsnjkh0v3ss539uq7"); // add session id you want to set
$this->Session->id();
$this->Session->read("key"); // hhoorray worked :)
with SessionComponent id() function needs to be called twice once with session id to set session_id(); and second time to start cake session.
First call does not really start the session ... I dont know how Cake Guys missed it .....
Upvote if this works for you.

Resources