SPContext.Current.Web.CurrentUser returns misleading value - security

I'm trying to find out current user name for my sharepoint application. There are more that one way how to do this. However the sharepoint way returns misleading value.
System.Security.Principal.WindowsIdentity.GetCurrent().Name // returns MY_COMPUTER\\my_user
HttpContext.Current.User.Identity.Name // returns MY_COMPUTER\\my_user
HttpContext.Current.Request.ServerVariables["AUTH_USER"] // returns MY_COMPUTER\\my_user
Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName // returns SHAREPOINT\\system
What is the cause of this behavior? Will I encounter problems if I'll use non-sharepoint way?

Are you browsing as the admin account that you used to install the system? SharePoint will "helpfully" rename that SHAREPOINT\System. Use a different account and all of the methods will return the same value.

This is expected if the user is the application pool account running the current web application.
BTW, it's supposed to be the same name as displayed in the welcome control (upper left control)

The problem is because you are probably getting the current user from an elevated SPWeb inside a RunWithElevatedPrivileges code. You can use the snippet below to get the real user
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
{
string currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
}
}
});
This will show the real user name instead of the SHAREPOINT\System user.

I think you might have include this code under SPSecurity.RunWithElevatedPriviliges. Check it out once. I am not sure though

The other way SPWeb.CurrentUser could return SHAREPOINT\system is if the web is elevated, though I'm not sure why SPContext.Current would be elevated. On what kind of page are you seeing this behavior?

Related

JSOM: get_isSiteAdmin () is not distinguishing between users and administrator of site collection

if (user.get_isSiteAdmin())
{
document.cookie = "licence=yes";
}
I am using user.get_isSiteAdmin() but its always giving value false I can not give permission to site site collection
Site Collection - Full Control
in AppMenifest.xml file
is there any other way to get site administrator ?
#user11869887,
Just have a test this JSOM function on my SPO environment, it works fine here.
you may need to explicitly initialize the object/properties, or it will always return false as the related property is null.
BR

UserCustomAction does not fire for non-tenant admin in SharePoint online

I have written a fairly straight-forward JavaScript for SharePoint Online that I am deploying as a user custom action into the root site collection using CSOM.
The following code is the block I am using for provisioning the script to the site collection:
public static void ProvisionScriptLinkCustomAction(ClientContext ctx, string name, string url)
{
Site site = ctx.Site;
ctx.Load(site.UserCustomActions);
ctx.ExecuteQuery();
foreach (UserCustomAction action in site.UserCustomActions)
{
if (action.Name == name)
{
action.DeleteObject();
break;
}
}
ctx.ExecuteQuery();
UserCustomAction customAction = site.UserCustomActions.Add();
customAction.Location = "ScriptLink";
customAction.Name = name;
customAction.ScriptSrc = url + "?" + Guid.NewGuid().ToString();
customAction.Update();
ctx.ExecuteQuery();
}
I am logged in as the tenant administrator when deploying and initially testing the custom action. Everything works as expected until I log in as a user that is not the tenant admin. When logged in as any other user that is only a site collection administrator or lower, the custom action does not fire and all of my efforts are for naught.
This feels like a configuration or permissions issue to me but I am at a loss to begin to know where to look to rectify this issue.
Any helpful thoughts would be greatly appreciated!
Turns out I had console.log calls in my JavaScript. Some versions of IE apparently do not know how to log to the console when in browser mode without debug tools which presumably throws an uncaught and unlogged exception. Removing the console.log statements made the issue go away.

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.

EnsureUser not returning valid User

I am trying to get a user back in SharePoint Client OM using EnsureUser. My code is:
ClientContext clientContext = new ClientContext(siteUrl);
User spUser = clientContext.Web.EnsureUser(user);
Where siteUrl and user are both strings set as appropriate.
The result is spUser is the shell of a User object but all its properties (for example Email, Title, etc.) are not initialized. In VS they are showing {"The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
What would be causing this? I thought EnsureUser would create the user if it is not already there. I know in Server OM sometimes you need to use "AllowUnsafeUpdates", is there something like that for Client OM?
It is almost a year late, but just in case someone else is searching for the same answer.
After getting a reference to the user object you need to do the following before accessing the properties of the user.
clientContext.Load(spUser);
clientContext.ExecuteQuery();
or if you want to get the email and title only to reduce the pay load.
clientContext.Load(spUser, u => u.Email, u => u.Title);
clientContext.ExecuteQuery();
Basically, it establishs a request to the SharePoint Web and ask for the properties of the spUser. The request will be send when ExecuteQuery() is called.

Strange behavoir of RunWithElevatedPrivileges in Console Aplication with FBA

I have a named site collection where FBA is on und i use ActiveDirectoryMembershipProvider.
We have a farm administrator domain\administrator. He is not explicitly sitecollection administrator.
I created a sample console application that I run under the domain\administrator account.
In the code is something like that:
using (SPSite site = new SPSite(serverUrl))
{
using (SPWeb web = site.OpenWeb())
{
Console.WriteLine(web.CurrentUser.LoginName);
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
string userName = "domain\\testuser";
SPUser spUser = web.EnsureUser(userName);
SPGroup group = web.SiteGroups["GroupName"];
group.AddUser(spUser);
group.Update();
}
}
The console output is domain\administrator however I become an AccessDenied exception when I try to add user to the group.
However when I run this with RunWithElevetadPrivileges (which according to all posts I read should have no influence in console app) and set AllowUnsafeUpdates = true (the same story) the code goes smoothly through, no exception thrown and the user is added to the group. The interesting thing is that the user that is written to the console output is still domain\administrator.
So my question is: WTF? Is there a better way? Why is this happenning? Has anyone already had this problem? Should I use another membershipprovider?
Small hint: When the FBA is off I become no exceptions.
RunWithElevatedPrivileges runs code with permissions of user that the application pool runs. It can be other than Administrator. Are you sure you get the same result with RunWithElevatedPrivileges?
Anyway, a better, more reliable way of elevating privileges is to pass system users User token in SPSite constructor. Try it.

Resources