System.Net.WebException: The request failed with HTTP status 401: Unauthorized - vb.net

Ok, so I have this .NET 1.1 application (written by someone way back) which is like a document repository and it worked fine in the past. I suddenly get this error when trying to search for items/documents:
Page: /CPDEPforIT/SearchResults.aspx
Error:
System.Net.WebException: The request failed with HTTP status 401:
Unauthorized. at
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream responseStream, Boolean
asyncCall) at
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters) at
CPDEPforIT.InktomiSearchService.soapSearchService.getSearchResults(SearchInput
in0) at CPDEPforIT.SearchResults.GetDatasetForSearchQuery(SearchInput
searchInput) at CPDEPforIT.SearchResults.Page_Load(Object sender,
EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at
System.Web.UI.Control.LoadRecursive() at
System.Web.UI.Page.ProcessRequestMain()
I don't remember any changes. Could this have been caused by something external to the application (IIS configurations/permissions, Server, Database)?

There are several things you need to verify.
Does the web service you are trying to access allow Anonymous Access? Authentication can be tricky for web-to-web calls
What is the web application running under, IWAM_xxx or IUSR_xxx? Or are you using an application pool running under a specific identity?
You may want to make sure your web application server's ASPNET or NETWORK SERVICE accounts can access your web service server.
If you want to get it working you could just provide an account for Anonymous Access...
Thanks!

I have also faced this type of issue before. In my case permission to the code folder works. Please check the folder permissions and then try with the IIS permissions.

Related

System.Security.Authentication.AuthenticationException: System error

I'm hosting an ASP.NET Core 3.1 web app with IIS 10, and it's throwing the following exception when trying to hit my API's through Postman:
System.Security.Authentication.AuthenticationException: System error.
at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, Object resource)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
When using Postman on the machine running the web app, I can make successful HTTP requests and not have any issues. It seems to only be happening when trying to make external requests, but the error text is extremely unhelpful and I'm not sure where to begin diagnosing. As far as I can tell, the directory containing the web app project files doesn't have any specific security restrictions and the Application Pool is using an account with sufficient permissions to access and use them.
Has anyone seen error text like this before, or have any idea what the issue might be?
As it turns out, this exception was being thrown as a result of an incorrect database connection string. This particular request checks against a local database to ensure the user exists there.
Strangely enough, I've encountered this same type of issue before (where a database connection string is broken / changed at some point), but the resulting exception was much more specific in its Exception text and stack trace. The only thing I can't explain here is why the above error is so generic.

401 Unauthorized while ExchangeService.SubscribeToPushNotifications

Hi I have written an standalone Windows Forms application which uses EWS (Exchange Web Services) Managed API to listen to the new mail event on a particular email id. I am using impersonation. This is a part of my code:
service = new ExchangeService(SyncSettings.ExchangeServerVersion);
service.Credentials = new WebCredentials(userid, password);
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserId);
service.Url = new Uri(exchnguri);
FolderId[] folders=new FolderId[1];
folders[0] = new FolderId(WellKnownFolderName.Inbox);
EventType[] events = new EventType[1];
events[0] = EventType.NewMail;
subscription = service.SubscribeToPushNotifications(folders, new Uri(listenUri), notificationInterval, "", events);
On Exchange Server side, I have provided one user account privileges to impersonate another user account.
When I run app in one environment it works fine. But when I run it in another it gives following error:
Immediate Stack Trace
===================================================================================
Microsoft.Exchange.WebServices.Data.ServiceRequestException : The request failed. The remote server returned an error: (401) Unauthorized.
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request)
at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
at Microsoft.Exchange.WebServices.Data.ExchangeService.SubscribeToPushNotifications(IEnumerable`1 folderIds, Uri url, Int32 frequency, String watermark, EventType[] eventTypes)
at com.org.app.Class.startListeningPushNotifications(String listenUri, Int32 notificationInterval) in c:\SW\app\Class.cs:line 156
Inner Exception 1 : Stack Trace
-----------------------------------------------------------------------------
System.Net.WebException . The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.GetResponse()
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request)
The only difference I observe in two environments is:
In first environment I login owa (Outlook Web Access) using domainx\userx, and to send mail to self account (that is, to the account with which I have logged in) I put userx#domainx.com in to field
However in second environment I login owa using domainxdc\userx (notice 'dc' in domainxdc), and send self mail with userx#domainx.com in to field. (notice no 'dc' in domainx.com)
I dont think that is giving me 401 Unauthorised, since I can login to owa using both impersonating and impersonated account. And I have given impersonating privileges in 2nd environment in exactly the same way as in 1st environment.
So why I am getting 401 Unauthorised ?
We are using Exchange Server 2007 and Windows Server 2008 SP2.
Here's something to try--might work:
service.CookieContainer = new CookieContainer();
I'm not very clear on why this helps, and in my case, it was going against Exchange Online, not your on-prem E2007. Might help; can't hurt. There was a blog post on this, but not sure if this will apply to your case.

How to login to Confluence when kerberos authentication is used programatically

We have Confluence Server 4.1 version installed. It is using AD authentication (Kerberos/Windows Security).
When we enter the confluence server URL in the address bar of browser, then it shows following pop-up windows for entering the credentials.
Users access Confluence through their local machines when they’re logged onto the domain. They are already logged into the domain, so are not prompted for a login. Users can easily view, add pages in Spaces.
We have followincg C# code to connect to Confluence, but it could not connect.
....
ConfluenceSoapServiceService service = new ConfluenceSoapServiceService();
service.Url = "http://confluence/rpc/soap-axis/confluenceservice-v2";
service.UseDefaultCredentials = true
Token token = service.login(username, password);
....
It throws following exception from the last line while calling serviec.login() method:
Error connecting to Confluence server url ''. Please check ServerAddress, Username and Password. System.Web.Services.Protocols.SoapException: com.atlassian.confluence.rpc.AuthenticationFailedException: Attempt to log in user 'null' failed - incorrect username/password combination.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ConfluenceAPIWebsServiceVersion2.ConfluenceSoapServiceService.login
Remote API (XML-RPC & SOAP) was already enabled. Basically, I wanted to login and get the token - which can be later passed for calling other functions of the soap API.
Could anybody shed some light on how to connect\login to Confluence?
Ref: https://answers.atlassian.com/questions/7674/does-the-appfusions-kerberos-sso-authenticator-for-confluence-work-with-the-confluence-remote-api

"Key not valid for use in specified state" Error for .Net 4.5 MVC 4 Application

To preface this question, please excuse me if I am getting any of my terminology wrong. The technology is very new to me.
I have a website in MVC 4, .Net 4.5 built with VS 2012 hosted on IIS7 and have used the "Identity and Access" wizard to configure authentication using a business identity provider. I have entered a path to an STS metadata document similar to:
https://xyz.mycompany.com/app/FederationMetadata/2007-06/FederationMetadata.xml
The site is currently hosted under three different realms. The first is my local development environment, second is standard integration testing and third is development.
http://localhost/myapp
http://sit.mycompanytest.com/myapp
http://dev.mycompanytest.com/myapp
It is important to note that the "dev" sub-domain is in a web farm or load balanced or something. I do not currently know the exact details of the load balancing architecture.
When I navigate to any of the above sites using IE 10 I am redirected to a login screen where I enter my credentials and gain access to the given site.
But, on the "dev" sub-domain, when navigating around the site using links and form submissions I eventually will get the following error:
Key not valid for use in specified state.
The stack trace of the error is:
[CryptographicException: Key not valid for use in specified state.]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +397
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +90
[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +1158198
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +173
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +756
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +100
System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +668
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +164
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I suspect the error is happening when the load balancer changes servers.
And, have been considering the 2nd workaround solution from the following web site: (http://blogs.msdn.com/b/distributedservices/archive/2012/10/29/wif-1-0-id1073-a-cryptographicexception-occurred-when-attempting-to-decrypt-the-cookie-using-the-protecteddata-api.aspx). But, the web site states that the solution is for .Net 4.0.
Will that solution work for .Net 4.5? And, if not, how can I fix the error?
I was able to fix the error by following the instructions in the following post by Vittorio Bertocci:
http://www.cloudidentity.com/blog/2013/01/28/running-wif-based-apps-in-windows-azure-web-sites-4/
Basically, I had to enable web farm cookies using the Identity and Access Tool.
In VS 2012, right click the project > select Identity Access > select the Configuration tab > check the Enable web farm ready cookies check box > click OK
IMHO the loadbalancing is the problem. You have to make sure the farm shares the same machine key. This can be done at machine level or in the web.config of your application.
Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:
Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();

"Cannot get Membership Provider with name xxx" Error in SharePoint 2010 FBA

I have a SharePoint 2010 web application that I'd like to use a custom membership provider with for authentication in an extended internet zone; however, I end up receiving the following error:
System.ServiceModel.FaultException`1 was unhandled by user code
Message=Cannot get Membership Provider with name xxx. The membership provider
for this process was not properly configured. You must configure the membership
provider in the .config file for every SharePoint process.
Source=Microsoft.IdentityModel
Action=http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault
StackTrace:
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.ReadResponse(Message response)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst)
at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo)
at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForFormsAuthentication(Uri context, String membershipProviderName, String roleProviderName, String username, String password)
at Microsoft.SharePoint.IdentityModel.SPClaimsUtility.AuthenticateFormsUser(Uri context, String userName, String password)
at Fellowes.Commerce.Site.Layouts.Fellowes.Commerce.Site.Authentication.SignInControl_Authenticate(Object sender, AuthenticateEventArgs e)
at System.Web.UI.WebControls.Login.AttemptLogin()
at System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
I have put the membership information in the Default Zone config, the Internet Zone Config, the Token Service config and the Central Administration config, but it is still complaining that I don't have the membership provider in the config for every SharePoint process. Is there another process that I've missed? Everyone else who received this error missed adding the entry in the token service, but I have already added it there. I am stumped!
I was having the same issues with getting my FBA setup. I essentially started over and followed this blog post step by step and everything worked out. I swore I did the exact same things on my own, still a mystery to me.
So it turns out that I didn't have the Claims to Windows Token Service started which is located in Central Administration > Manage Services On Server. Once I turned that on, it started working. Setting up the SQLMembershipProvider as Matt suggested got me pointed in the right direction, but it didn't turn out to the ultimate solution.