401 Unauthorized exception throws on Sharepoint Webpart using DataContext - c#

I'm using the below code to create a new instance of Sharepoint datacontext:
spDataContext con = new spDataContext(new Uri("http://mysite/subsite/_vti_bin/ListData.svc"));
con.Credentials = CredentialCache.DefaultCredentials;
Then I try fetching the items by using
var result = con.testingList.ToList();
Then Below error shows:
"401 UNAUTHORIZED"
Here's the screenshot of the error:
But if I change the credentials by providing the sharepoint admin username and password, I am able to fetch the items.
con.Credentials = new NetworkCredential(username, password);
But the problem is: I want to use the current user's credentials instead of administrator account, since not all the items are supposed to be seen by current user.
Some addition information from the IIS:
At first, all authentication methods are enabled, then I tried turning off basic and digest authentication to see if it helps, but the exception still throws.
So how to fix this problem??

Check what account you are actually connecting with by inspecting a breakpoint, writing to a log or checking the server's audit trail/Logs (IIS/SharePoint) - are you sure it's a valid account and not an IUSR_xyz IIS account or something like that? Also check that you are not hitting a Kerberos "double hop" if you are working with a distributed architecture. This can often trip you up when adding another server/service to the mix.

In order to get this to work, you should configure the Authentication options in IIS as follows:
Anonymous Authentication - DISABLED
ASPNET Impersonation - DISABLED
Windows Authentication - ENABLED
You can use the CredentialCache.DefaultCredentials, but I would suggest switching from using the WCF services to using CSOM (Microsoft.SharePoint.Client).

At last the reason was:
I don't have the System.Web assembly in the class library, so the system was unable to get the CredentialCache.DefaultCredentials.

Related

twitter integration in C# error

I want to integrate twitter in my ASP.Net web site with C# . I want to implement a profile page in which user should be able to sign in from twitter. After clicking on "Sign Up via Twitter" Button. I have made a twitter application and i am doing this thing with OAuth. After getting user details i want to add them to my SQL Server Database(So that in future user can sign in using these details).
IT gives an exception at runtime.The exception is
The remote server returned an error:(403) Forbidden.so please answer if you have done this kind of stuff.
I have already search all around on the internet,am i doing something wrong here?
Add the following line:
request.UseDefaultCredentials = true;
This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.
It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
Hope this helps.

Why am i getting authorization errors while using a personal access token?

I'm using the Visual Studio Team Services .NET libraries to perform source control through a class library of mine. I'm also using a personal access token for authentication, previously set through the VSTS web client.
I'm trying to perform basic actions like check in, out, adding pending changes, create folder mappings etc, and i'm getting an "attempted to perform an unauthorized operation" error when i previously add no problem doing these tasks. I was running my .dll on the server it's supposed to be running when it's done and because i was getting this error i tweaked a few lines of code and then just tested the whole thing on my machine again. It doesn't work anymore at all.
What's weird, though, is that when i try to change the working folder mapping for example, i get this error but the new local path gets assigned just fine.
Any reason why an authenticated VSTS user would have these problems?
Using PAT (personal access token) to authorize your .NET libraries, you should VssBasicCredential, such as below example:
string personalAccessToken = "bnsz6p2efh3vljhjoay4rnaznliygu9vngoqgcwel7gwlati8cxq";
VssBasicCredential credentials = new VssBasicCredential("", personalAccessToken);
More details, you can refer .NET client libraries.
Besides, you can also use Alternate authentication credentials. VSTS account -> security -> Alternate authentication credentials (https://account.visualstudio.com/_details/security/altcreds) -> Enable alternate authentication credentials -> set secondary username and password -> save.
Then you can authorize your .NET libraries by:
NetworkCredential credentials = new NetworkCredential("secondary username", "password for secondary username");
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://account.visualstudio.com"), credentials);

403 when connecting to Exchange Online

I am trying to use EWS on an Office 365 account however I get a return of (403 Forbidden)
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("mv003237", "correctpw","domain");
service.AutodiscoverUrl("mv003237#domain.co.uk");
To login and view the Webservices file on outlook.com/EWS/Exchange.asmx I need to authenticate with mv003237#live.domain.co.uk
I have tried several combinations of this and still get the same error message.
Has anyone had a similar experience of connecting to an office 365 account before?
My WINDOWS login for this account does have a domain of RDG-HOME but I haven't seen a domain for login into OWA.
Many thanks in advance
If you've already removed the domain name (as Matt suggested in his comment) the one thing that remains is to automatically follow redirects in the autodiscover process.
Change your last line to
service.AutodiscoverUrl("mv003237#domain.co.uk", redirect => true);
to follow the redirection response that Exchange Online sends.
So the complete sequence then becomes:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("mv003237", "correctpw");
service.AutodiscoverUrl("mv003237#domain.co.uk", redirect => true);
Cannot comment due to low reputation score and hence responding as an answer.
Are you able to login into OWA with "mv003237#domain.co.uk"? If yes, have you tried by hardcoding Url instead of using Autodiscover to understand if issue is with Autodiscover or EWS. Try following instead of autodiscover call:
service.Url = new Uri(#"https://outlook.office365.com/ews/exchange.asmx");
If above works fine, subscribe to RedirectionUrlValidationCallback with AutodiscoverService and see which redirected URL is throwing 403. Or enable verbose logging with Trace* properties present on service object.

User Permission Mask from NetworkCredentials

Although I am currently developing this WinForms application on our Sharepoint server I intend for the finished program to function from any computer on the Domain. I'm using the WSS web services to get all the information I use from Sharepoint.
I have written some code which will check Sharepoint Permission masks, with logical OR against mask, for all the permissions it covers but I am having trouble returning the Sharepoint mask for the current user. I would like users to be able to log right in through Windows Authentication so this was my immediate idea.
NetworkCredential credentails = CredentialCache.DefaultNetworkCredentials;
var userInfo = userGroupService.GetUserInfo(credentails.UserName);
However although I am able to return the permission collection for the entire Sharepoint site with DefaultNetworkCredentials (as in bellow snippet) the properties are empty strings, so I can't use it to get the UserName.
permissionService.Credentials = CredentialCache.DefaultNetworkCredentials;
permissionService.Url = "http://localhost/mySite/_vti_bin/Permissions.asmx";
// Web service request works
XmlNode node = permissionService.GetPermissionCollection(siteName, "Web");
// But I need to identify current user from this collection somehow still
I read that Windows Authentication suffers from a double-hop issue, which I want to avoid, but as I am developing on the server Sharepoint & IIS are running, I can't see this causing an immediate issue.
Is there a way around this or a better way to get the current users permission mask?
If the current user for wss will always be the same as the user currently logged on to the pc
var userInfo = userGroupService.GetUserInfo(Environment.UserDomainName +#"\"+ Environment.UserName);
or to get the permissions for the currently logged on user
XmlNode currentUserPermission = userGroupService.GetRolesAndPermissionsForCurrentUser();
You are dealing with an issue where the authentication cannot move beyond one remote host; this is known as the "one-hop" limitation.
To overcome this, you have to get into "Constrained Delegation," where a computer/account are expressly authorized to receive and accept authentication credentials from another computer/account. This is set up in Active Directory by defining the appropriate Service Principal Names (SPN's) on either "end" of the delegation.
You can get more details about Constrained Delegation here.
Good luck! CD can be a bit of a pain to set up, so tread carefully.

"HTTP status 401: Access Denied" error for web service even when the virtual directory allows Anonymous access

i have a web service hosted on another server with the Anonymous Access CheckBox in IIS is already checked. when my local web application is trying to access the web service, i still get the "The request failed with HTTP status 401: Access Denied." error. my web application is calling the web
service like the following:
MyObject.WebService ws = new MyObject.WebService ();
ws.Retrieve(someParams);
what am i missing here?
Here is a good reference on diagnosing 401 errors.
From that, one place to start is looking at the credentials you configure for the anonymous user. If they are incorrect (if perhaps the user password was changed elsewhere) you will get an HTTP 401.
Make sure your directory permissions are also set to allow everyone read access. A lot of times doing local dev work I will forgot that the directory being accessed has a seperate set of permissions that need to be altered.
Cheers!
Check this http://www.c-sharpcorner.com/UploadFile/mahesh/40107282006095201AM/401.aspx.
//Assigning DefaultCredentials to the Credentials property
//of the Web service client proxy (myProxy).
myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials;
This code worked for me.
have you try un selecting the allow iis to control password some times that get out of sink.
try the site and it may work. you sould be able to reenable control after that
Try the following (note the PreAuthenticate thingy):
MyObject.WebService ws = new MyObject.WebService();
ws.PreAuthenticate = true;
response = ws.Retrieve(someParams);
For more detailed explanation why this may work you can reference following answer here http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/3ae9753d-2d97-45b9-9ba2-6d551fe60a48/.
I think what might be happening is that you are getting a 401 - permission denied but as to whom the permission is denied to is unclear. I am guessing at this point you have checked the NTFS permissions on the machine, and have confirmed that you do have access.
Next I would look at what account the application pool uses. If it is the default setup, it will probably be the NT Network Service Account. If that is the case, confirm that the account does have access to the application directory. If that is also the case it might perhaps be a COM+ security setting. By default your network service account does not have permission to remotely launch components. If this is the case you will be seeing errors in the system and security log that will say things link, "Unable to launch component "
Looking at the IIS log files and the system and security event logs on the iis server often yield more clues.
Hope it helps
Best Regards
Rihan Meij

Categories

Resources