SharePoint session persist across several users? - sharepoint

I have a custom web part that starts by getting a current user login name like this:
protected static string iAm = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split("\\".ToCharArray())[1].ToLower().
Then it passes this string to a bbl class and fetches a user id:
`IDataReader _drInfo = cisf_BLL.bll_MyInfo.drGetMyInfo(iAm);
while (_drInfo.Read())
{
iUser_Ident = _drInfo.GetInt32(30);
}
`After that it passes the user id integer to another method that fetches user's training record:
_drUserTraining = bll_Training.drGet_required_training_records(iUser_Ident);
_drUserTrainingCompleted = bll_Training.drGet_completed_training_records(iUser_Ident);
This information is then displayed in a tab container with three tab such as "Overdue", "Required", and "Completed".
The problem I'm having is this: I'm logged into SharePoint collaboration site with my domain user name and all my training is displayed just fine. If my someone else then logs in to the SP Portal that user sees my training and not his, even though this user has logged in with his unique credential using a common access card, just as I.
Somehow some strange session seems to persist and I was hoping someone out here has encountered this anomaly.
Thanks in advance!
Risho

You are misusing static - a static property is stored once per web server process, not once per user.

Not an answer, but code improvement: there is much simplyer way to get current user name/id
SPUser user = Microsoft.SharePoint.[SPContext][1].Current.Web.CurrentUser;
user.ID;
user.Email;
user.Name
user.LoginName;
user.Grups;
....
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser_members.aspx

Related

IBM Domino 10 - Java XPage create session or compare credentials of another user

I'm writing Java code in an XPage Rest Service basing on https://setza-projects.atlassian.net/wiki/spaces/RSD/pages/44007659/IBM+Domino which is an REST service written in Java used to handle Resource Reservations database. However the way it currently works, it creates the reservations for the current session user only:
private JsonObject createIntanceAppointment(ResourceDefinition rd, Database reDatabase, Date dtStart, Date dtEnd, String subject) throws NotesException {
Session session = reDatabase.getParent();
Name nnOrganizier = session.createName(session.getEffectiveUserName());
Name nnREsource = session.createName(rd.getFullName());
DateTime dt_startDateUTC = session.createDateTime(dtStart);
DateTime dt_endDateUTC = session.createDateTime(dtEnd);
Document doc = reDatabase.createDocument();
doc.replaceItemValue("form", "Reservation");
doc.replaceItemValue("Purpose", subject);
doc.replaceItemValue("ReservedFor", nnOrganizier.getCanonical());
doc.replaceItemValue("ResourceName", nnREsource.getAbbreviated());
doc.replaceItemValue("ResNameFormat", nnREsource.getAbbreviated());
I'm doing a very similar integration with Domino, although I'd prefer to have the reservations created for individual users (they provide their username & password on the room-booking application on a touch screen).
I could just authenticate as the user in my REST client, but if I understand the installation requirements for that RoomZ api correctly, the 'api managing user' needs to be exclusively signed to the database, so I would need to do that for every user in Domino that could make reservations.
I tried using NotesFactory.createSession("", "user", "password"); but that doesn't work, it gives Cannot create a session from an agent error
If I cannot create another session, is there any way I could verify that the username and password passed to the API in the payload is correct (to verify if the user can login)? Then I could just set the organizer/reserved for to this user.
Also, is there any way to make these reservation also appear in the organizer's Notes calendar? Currently they are succesfully created in the Reservations database and all, but the organizer is unaware of them despite he's assigned to the reservation.
You do not need to create a session for every user. The important thing is the nnOrganizer = session.createName(" ") which should contain the user. Probably you'll also need to set additional fields like chair or from for the reservation.
If you want to have some entries in the organizers calendar, send them a proper invitation or create a calendar entry in their mailfile.

Logged in user can only access 1 page?

Using Orchard 1.6 Iv created a new role 'FactoryWorker'. When this user logs in from the front end I want them to be navigated to one page only.
OrchardLocal/System/ManufacturedProducts
I have set this page to be a print screen of the order details so the factory worker will know what products to get ready for ship out & they wont be able to navigate as no menu appears, but also need the other pages blocked incase the user decides to enter the URL of a page they arnt allowed access to.
This is the only page I want this particular user to be able to access(after they login), and I have added a logout button, which logs out the user and returns them to the home page.
So iv been looking through editing a role, with permissions and content etc...but this all seems to be applying to forms and content in general. where the user can access any content type etc...
So can someone advise me on how to do this?
thanks for any replies
UPDATE
I forgot to mention that this is not a content type, item or part I am talking about.
I have created my own controller & View & VM which is accessible from the dash board (using the AdminMenu, which brings the admin user to OrchardLocal/System/ManufacturedProducts)
I have looked at Orchard.ContentPermissions Feature but it only seems to allow me to 1)Grant permissions for others or 2)Grant permission for own content
any ideas?
You can use a Request Filter, (I do not know if it is the best way) :
FilterProvider – defines the filter applied to each request. Resembles the way default ASP.NET MVC action filters work with the difference that it’s not an attribute. All FilterProvider objects are injected into the request pipeline and are applied to all requests (so you need to check if the current request is suitable for your filter at the beginning of an appropriate method).
From : http://www.szmyd.com.pl/blog/most-useful-orchard-extension-points
So you could implement something like this
public class Filter : FilterProvider, IAuthorizationFilter {
private readonly IAuthenticationService _authenticationService;
public Filter(IAuthenticationService authenticationService) {
_authenticationService = authenticationService;
}
public void OnAuthorization(AuthorizationContext filterContext) {
//If route is the restricted one
if (filterContext.HttpContext.Request.Url.AbsoluteUri.Contains("OrchardLocal/System/ManufacturedProducts")) {
//Get the logged user
IUser loggedUser = _authenticationService.GetAuthenticatedUser();
if (loggedUser == null)
return filterContext.Result = new HttpUnauthorizedResult();
//Get the Roles
var roles = loggedUser.As<IUserRoles>().Roles;
if (!roles.Contains("FactoryUser")) {
//User is not authorized
return filterContext.Result = new HttpUnauthorizedResult();
}
}
}
}
Note: Untested code!
EDIT: Also you could invert the logic and check if the logged user has the role 'FactoryUser' and restrict its access to every page except the one they should see.
Your module can create a new permission (look at one of the permissions.cs files for examples), then create a role that has only that permission. Have your controller action check that permission (again, many examples found by finding usage of the permissions defined in one of the permissions.cs).
You can use the Content Permissions module. Using this module you can attach a content item permission part to a content type. This part allows you to choose which roles can see the content when you create it.

How to use a logged in person's credentials to search Active Directory?

I have a web app (.NET 3.5) which is sending notifications by email to users. In order to do this, I search Active Directory to find each person's email.
At the moment, I am hardcoding my own username and password like so in order to search AD:
Dim entry As New DirectoryEntry("LDAP://companyad", "myUsername", "myPassword", AuthenticationTypes.Secure)
Dim srch As New DirectorySearcher(entry)
srch.Filter = [String].Format("(&(objectClass=person)(sAMAccountName={0}))", "someOtherUsername")
Dim result As SearchResult = srch.FindOne()
Now, obviously, this is not ideal and I don't want those credentials hardcoded. My web app is using Windows Authentication. It also uses impersonation (as the logged in user) to access files and SQL Server. Is there also a way for me to "impersonate" the logged in user in order to search AD?
EDIT 1
I thought I'd better explain why I chose this answer. The problem turned out to not be the multi-hop issue or kerberos as it seems I have set these up correctly.
I had recently changed my app to only allow access to a certain group through the web.config settings. I had previously been only allowing access to myself. I set up the group and added myself to it. I then removed the hardcoded credentials and attempted to run the app WITHOUT RESTARTING my computer.
According to my network admin, I would not be logged on under that new group until I restarted my computer which I think is what was causing my problem. So, Preet's answer is actually the most accurate as I just needed to pass the LDAP path to DirectoryEntry.
EDIT 2
I also needed to register a Service Principal Name.
I ran this:
setspn -A HTTP/[dns name of the site] [machine name]
on my development machine.
Thanks to everyone else for their answers.
Doesn't
Dim entry As New DirectoryEntry("LDAP://companyad")
work?
Why not create a new user for this purpose alone? A user with only searching rights.
I set <identity impersonate="true"/> in my web.config and added the following code to my my page load event handler. It worked fine. Are you sure you are not dealing with a multi hop situation? In that case your app pool account needs to be configured for kerberos authentication to support impersonation in a multihop scenario. More info on this is here: http://support.microsoft.com/kb/329986
Response.Write(User.Identity.Name);
DirectoryEntry entry = new DirectoryEntry("LDAP://[mydomain.net]");
DirectorySearcher srch = new DirectorySearcher(entry);
srch.Filter = string.Format("(&(objectClass=person)(sAMAccountName={0}))", "[user]");
SearchResult result = srch.FindOne();
Response.Write(result.Path);
If you wish to use the Windows logged in user account as the credentials against AD, you have to use the following:
public bool IsExistingUser() {
DirectoryEntry de = new DirectoryEntry(Environment.UserDomainName)
DirectorySearcher ds = new DirectorySearcher(de)
ds.Filter = string.Format("((objectClass=user)(SAMAccountName={0}))", Environment.UserName)
try
SearchResult sr = ds.FindOne();
if (sr != null && sr.DirectoryEntry.Name.Contains(Environment.UserName))
return true;
catch (DirectoryServicesCOMException ex)
catch (COMException ex)
throw new Exception("Can't find logged in user in AD", ex);
return false;
}
Assuming this code would compile and run, it will verify whether the existing logged in user is known by your Domain Controller.
Impersonation is discouraged as it lets litteral password strings travel in your network. So, try to avoid it as much as possible.
EDIT Here's a pretty useful link for AD: Howto: (Almost) Everything In Active Directory via C# I found this post awesome!

Accessing the user from a liferay portlet?

I'm attempting to develop a portlet for liferay.
How can I get access to the username and password (and other data liferay has) of the user that's currently logged in?
I'd also like to be able to execute some code when users change their password.
You can get the User ID by calling getRemoteUser() in the PortletRequest object. This is defined by JSR-168 therefore it's cross-portal compatible.
Once you have the ID you can fetch the additional informations by calling getUserById() (a Liferay specific service). This is something not covered by Portlet API specification, so it locks you to the Liferay.
Liferay Specific stuff, here is a code sample to be written in your Portlet Class to retrieve the User:
ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = themeDisplay.getRealUser(); // it gives you the actual Logged in User
//you can also use
// User user = themeDisplay.getUser(); // this would fetch the User you are impersonating
long userId = user.getUserId();
String userName = user.getEmailAddress();
Alternatively;
long userId = themeDisplay.getRealUserId(); // themeDisplay.getUserId();
User user = UserLocalServiceUtil.getUser(userId);
Impersonate User:
Liferay has a concept that admins (or persons with the correct set of permissions) can impersonate a particular user of the portal. Through this they can see how the portal looks to that user.
For executing the code when user change their passwords:
One approach would be to create a hook plugin and overriding the services by extending the UserLocalServiceWrapper class. Then checking for the password change and executing your code inside the your custom class.
Hope this helps.
Or you can just use javascript:
Liferay.ThemeDisplay.getUserId()
There are many nice to haves in the Liferay namespace, take a look at the not so well documented API:
https://www.liferay.com/community/wiki/-/wiki/Main/Liferay+JavaScript+API
https://www.liferay.com/web/pankaj.kathiriya/blog/-/blogs/usage-of-liferay-js-object
Also, take a look at the web services available under localhost:8080/api/jsonws which you can invoke with a javascript call:
Liferay.Service(
'/user/get-user-by-id',
{
userId: 10199
},
function(obj) {
console.log(obj);
}
);
One simple and easy way to get the user in Liferay is PortalUtil.getUser function.
User user = PortalUtil.getUser(portletRequest);

Getting the NT-ID of a user in SharePoint

What is the simplest way to get the NT-ID of a user in a C# application? I would probably need to get it only having a name of the user, or maybe an email address.
Most of the time, you can get it from the current web, for example:
string login = SPContext.Current.Web.CurrentUser.LoginName
string mail = SPContext.Current.Web.CurrentUser.Email
From within SharePoint, you can get a user's Active Directory information (including display name and email) using SPUtility.ResolveWindowsPrincipal:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.utilities.sputility.resolvewindowsprincipal.aspx
For example:
SPPrincipalInfo pi = SPUtility.ResolveWindowsPrincipal(SPContext.Current.Site.WebApplication, "MYDOMAIN\\myusername", SPPrincipalType.All, false);
Outside of SharePoint, you want to look at the System.DirectoryServices namespace.

Resources