Sharepoint Client Object Model edit Author and Editor fields - c#

I'm trying to put the current user logged in my MVC 5 application (with windows authentication) into the Author and Editor fields of a new ListItem.
I didn't succeed to just pass the user credentials to the SharePoint Client context, so I tried to edit these two fields instead using SharePoint Client Object Model
using SP = Microsoft.SharePoint.Client;
...
SP.User SPuser = context.Web.EnsureUser(Request.LogonUserIdentity.Name);
//SP.User SPuser = context.Web.EnsureUser("mydomain\\someuser"); //same result as above
context.Load(SPuser);
context.ExecuteQuery();
SP.FieldUserValue userValue = new SP.FieldUserValue();
userValue.LookupId = SPuser.Id;
SP.ListItem documentLi = documentFile.ListItemAllFields;
...
//We don't want the application pool identity here, but the current user
documentLi["Author"] = userValue;
documentLi["Editor"] = userValue;
documentLi.Update();
context.ExecuteQuery();
It works fine in localhost, but nothing happens when I try it on the server : these two fields keeps the application pool identity.
What did I miss ?

I found what was the problem : in localhost the application pool identity is my user which has full control on the sharepoint list unlike the application pool identity in IIS (it just had contribute permission), it worked fine once I promoted it with full control as well.

Related

How to return the Windows Authenticated username instead of the App Pool user in IIS? [duplicate]

In a forms model, I used to get the current logged-in user by:
Page.CurrentUser
How do I get the current user inside a controller class in ASP.NET MVC?
If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.
I found that User works, that is, User.Identity.Name or User.IsInRole("Administrator").
Try HttpContext.Current.User.
Public Shared Property Current() As
System.Web.HttpContext
Member of System.Web.HttpContext
Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.
Return Values:
The System.Web.HttpContext for the current
HTTP request
You can get the name of the user in ASP.NET MVC4 like this:
System.Web.HttpContext.Current.User.Identity.Name
I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:
Request.IsAuthenticated tells you if the user is authenticated.
Page.User.Identity gives you the identity of the logged-in user.
I use:
Membership.GetUser().UserName
I am not sure this will work in ASP.NET MVC, but it's worth a shot :)
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
UserName with:
User.Identity.Name
But if you need to get just the ID, you can use:
using Microsoft.AspNet.Identity;
So, you can get directly the User ID:
User.Identity.GetUserId();
In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use
WebSecurity.CurrentUserId
once you add a using statement
using System.Web.Security;
We can use following code to get the current logged in User in ASP.Net MVC:
var user= System.Web.HttpContext.Current.User.Identity.GetUserName();
Also
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'
Environment.UserName - Will Display format : 'Username'
This page could be what you looking for:
Using Page.User.Identity.Name in MVC3
You just need User.Identity.Name.
Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.
This will get the current logged-in Windows user.
For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.
If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.
MembershipUser u = Membership.GetUser(LoginUser.UserName);
You can use following code:
Request.LogonUserIdentity.Name;
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
...
currentUser.IsInRole("Operator");
var ticket = FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket.Expired)
{
throw new InvalidOperationException("Ticket expired.");
}
IPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
If you happen to be working in Active Directory on an intranet, here are some tips:
(Windows Server 2012)
Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.
How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:
// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...
You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:
using (HostingEnvironment.Impersonate()){ ... }
You must also have impersonate set to true in your web.config:
<system.web>
<identity impersonate="true" />
You must have Windows authentication on in web.config:
<authentication mode="Windows" />
In Asp.net Mvc Identity 2,You can get the current user name by:
var username = System.Web.HttpContext.Current.User.Identity.Name;
In the IIS Manager, under Authentication, disable:
1) Anonymous Authentication
2) Forms Authentication
Then add the following to your controller, to handle testing versus server deployment:
string sUserName = null;
string url = Request.Url.ToString();
if (url.Contains("localhost"))
sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
sUserName = User.Identity.Name;
If any one still reading this then, to access in cshtml file I used in following way.
<li>Hello #User.Identity.Name</li>

LDAP search fails on server, not in Visual Studio

I'm creating a service to search for users in LDAP. This should be fairly straightforward and probably done a thousand times, but I cannot seem to break through properly. I thought I had it, but then I deployed this to IIS and it all fell apart.
The following is setup as environment variables:
ldapController
ldapPort
adminUsername 🡒 Definitely a different user than the error reports
adminPassword
baseDn
And read in through my Startup.Configure method.
EDIT I know they are available to IIS, because I returned them in a REST endpoint.
This is my code:
// Connect to LDAP
LdapConnection conn = new LdapConnection();
conn.Connect(ldapController, ldapPort);
conn.Bind(adminUsername, adminPassword);
// Run search
LdapSearchResults lsc = conn.Search(
baseDn,
LdapConnection.SCOPE_SUB,
lFilter,
new string[] { /* lots of attributes to fetch */ },
false
);
// List out entries
var entries = new List<UserDto>();
while (lsc.hasMore() && entries.Count < 10) {
LdapEntry ent = lsc.next(); // <--- THIS FAILS!
// ...
}
return entries;
As I said, when debugging this in visual studio, it all works fine. When deployed to IIS, the error is;
Login failed for user 'DOMAIN\IIS_SERVER$'
Why? The user specified in adminUsername should be the user used to login (through conn.Bind(adminUsername, adminPassword);), right? So why does it explode stating that the IIS user is the one doing the login?
EDIT I'm using Novell.Directory.Ldap.NETStandard
EDIT The 'user' specified in the error above, is actually NOT a user at all. It is the AD registered name of the computer running IIS... If that makes any difference at all.
UPDATE After consulting with colleagues, I set up a new application pool on IIS, and tried to run the application as a specified user instead of the default passthrough. Exactly the same error message regardless of which user I set.
Try going via Network credentials that allows you to specify domain:
var networkCredential = new NetworkCredential(userName, password, domain);
conn.Bind(networkCredential);
If that does not work, specify auth type basic (not sure that the default is) before the call to bind.
conn.AuthType = AuthType.Basic;

Why is my List.GetUserEffectivePermissions() method not working?

I'm developing a process in C# with the SharePoint 2013 Client Side Object Model. I need to retrieve the SharePoint List Permissions of a given user, that will be different than the user that is executing the code.
using SP = Microsoft.SharePoint.Client;
SP.ClientContext SpContext = new SP.ClientContext("SITEURL");
SP.Web SiteWeb = SpContext.Web;
SP.List Lst = SpContext.Web.Lists.GetByTitle("LIST");
var ClientUserEffPerms = Lst.GetUserEffectivePermissions(#"<domain>\<username>");
SpContext.Load(SiteWeb, S => S.EffectiveBasePermissions);
SpContext.Load(Lst, L => L.EffectiveBasePermissions);
SpContext.ExecuteQuery();
After this code executes, the ClientUserEffPerms.Value (BasePermissions) object does not represent the permissions of the given user correctly. The object isn't null, but it represents the user as having no permissions. The user has at minimum view and edit permissions and I can confirm this by viewing/editing List Items using the web browser as this user.
The code executing user has permission to enumerate permissions at both the Web and List level. I've confirmed this with the code below, both booleans resolve to true.
bool SvcUserHasSiteEnumPermsPerm = SiteWeb.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
bool SvcUserHasListEnumPermsPerm = Lst.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
Can anyone help me determine what is wrong with my GetUserEffectivePermissions() method?
When you call GetUserEffectivePermissions you need to pass in the full claims token version of the login name, which looks something like this:
i:0#.w|domain\user
You can get this by loading the LoginName property on a user object:
clientContext.Load(clientContext.Web.CurrentUser, i => i.LoginName);
clientContext.ExecuteQuery();
Of course, that's for the current user, so you'll need to acquire the user you actually want first.

Silverlight: Preventing authentication window / login prompt while connecting SharePoint with different credentials using DataContext (REST)

I'm programming a Silverlight client to consume a list in Sharepoint 2010 using REST. It's supposed to work as a gadget on users Windows desktop.
My requirement is, logging into Sharepoint with specific credentials instead of current logged user. It works fine with the source code I pasted down and I'm able to fetch the list content as expected, however, everytime I run the software, Windows shows a login box - authentication window to user before estabilishing a connection to Sharepoint.
If user skips it by clicking "cancel" the rest of software works normally.
So I need to prevent this login box.
ObservableCollection<ShoutBoxItem> allItems = new ObservableCollection<ShoutBoxItem>();
ShoutsProxy.TwitterDataContext context = new TwitterDataContext(new Uri(webServiceUrl));
context.HttpStack = HttpStack.ClientHttp;
context.Credentials = new System.Net.NetworkCredential(username, password, domain);
context.UseDefaultCredentials = false;
DataServiceQuery<ShoutBoxItem> query = DataServiceQuery<ShoutBoxItem>)context.ShoutBox;
query.BeginExecute(onGetShoutBoxItemsComplete, query);
So at exactly "query.beginexecute" line, a login box comes up immediately.
Any suggestions?
Greetings from Duisburg,
Alper Barkmaz
Well, I have found a workaround for this.
Instead of filling out a NetworkCredential object with login information, I post username and password at web service URL, http://username:password#domain.com/service.svc
And voila, there's no authentication prompt. The point was, my silverlight application was hosted in local html file with address starting with file://, thus transferring network credentials to target domain was having problems. So in this case, instead of dealing this inside Silverlight, I directly modified the URL and the result was brilliant.
Security: I believe httpclient breaks in, does authentication and removes the login information from URL, so the login information is not transferred over network as plain text. However, double checking this is better.
The new form of solution is,
ObservableCollection<ShoutBoxItem> allItems = new ObservableCollection<ShoutBoxItem>();
ShoutsProxy.TwitterDataContext context = new TwitterDataContext(new Uri("http://username:password#domain.com/service.svc"));
context.HttpStack = HttpStack.ClientHttp;
context.Credentials = new System.Net.NetworkCredential();
context.UseDefaultCredentials = false;
DataServiceQuery<ShoutBoxItem> query = DataServiceQuery<ShoutBoxItem>)context.ShoutBox;
query.BeginExecute(onGetShoutBoxItemsComplete, query);

Sharepoint connection with a username and password

i've searched during 2 days to resolve my problem but there is no way!
in fact, i'd like to connect to sharepoint using a user's account (there is no probleme when i use anonymous connexion).
i added a web reference of authentification and lists to use this code:
SPConnect.Authentication authSP = new SPConnect.Authentication();
SPLists.Lists spLists = new SPLists.Lists();
authSP.CookieContainer = new System.Net.CookieContainer();
authSP.AllowAutoRedirect = true;
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
if (loginSP.ErrorCode == SPConnect.LoginErrorCode.NoError)
{
spLists.CookieContainer = authSP.CookieContainer;
//object list = spLists.GetList("presentationAccueil");
SPSite oSiteCollection = SPContext.Current.Site;
SPList listeee = oSiteCollection.AllWebs["http://vmspprod:25401"].Lists["presentationAccueil"];
}
i get this erro NotInFormsAuthenticationMode when i execute
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
is there any other method to use a user's login and password?
Thank you in advance for your answers.
You need to configure your SharePoint server to use Forms Authentication (that's what the exception is telling you).
You didn't say which version of SharePoint you are targeting (WSS 3.0, SP 2007, SP 2010). Here is a link to an MSDN page that shows you how to configure your server to use Forms Authentication: http://msdn.microsoft.com/en-us/library/bb975136(v=office.12).aspx
If you cannot modify the server, then you will need to change your code to use whatever authentication mechanism the server employs.
I hope this helps.

Categories