Azure webhttprelaybinding authorization issue - azure

I have stumbled into an annoying azure wcf http relay issue, which i cant seem to be able to solve.
The issue arises when I set the security relayClientAuthenticationType to RelayAccessToken, which makes my endpoints unreachable due to a "Invalid authorization header: The request is missing WRAP authorization credentials" Error, whhich I Can't seem to solve.
If i set the security to "None", there are no issues.
I am currently using Postman to test the service.
Below areall the relevant details of the application(.net 4.6.2 console app), thanks in advance :)
App.config
<services>
<service name="XXXXX" behaviorConfiguration="servicebehavior">
<endpoint address="https://XXXXX.servicebus.windows.net/relayserver" binding="webHttpRelayBinding" contract="XXXXX" behaviorConfiguration="behavior" bindingConfiguration="default" />
</service>
</services>
<bindings>
<!-- Application Binding -->
<webHttpRelayBinding>
<binding name="default">
<security relayClientAuthenticationType="RelayAccessToken"/>
</binding>
</webHttpRelayBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="servicebehavior">
<serviceDebug httpHelpPageEnabled="false" httpsHelpPageEnabled="false" includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="behavior">
<transportClientEndpointBehavior>
<tokenProvider>
<sharedAccessSignature keyName="RootManageSharedAccessKey" key="XXXX" />
</tokenProvider>
</transportClientEndpointBehavior>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=https://XXXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXX" />
</appSettings>
Opening the host
var host = new System.ServiceModel.Web.WebServiceHost(typeof(XXXXX));
host.Open();
Console.WriteLine("Press ENTER to close");
Console.ReadLine();
host.Close();
Azure Relay Firewall settings
Allow access from all networks
Testing the relay: test method (interface)
[OperationContract, WebGet(UriTemplate = "?id={id}&key={key}", ResponseFormat = WebMessageFormat.Json)]
FakeData GetFakeData(string id, string key);
Test Results
If I set relayClientAuthenticationType to None, i get a json response as expected.
<security relayClientAuthenticationType="None"/>
If I set relayClientAuthenticationType to RelayAccessToken, I get an unauthorized error.
<security relayClientAuthenticationType="RelayAccessToken"/>
<Error>
<Code>401</Code>
<Detail>MalformedToken: Invalid authorization header: The request is missing WRAP authorization credentials. TrackingId:..</Detail>
</Error>

Issue has been fixed : I had a typo in the access token i made: Created a new access token in c# using the following method: learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token

Related

Azure Troubleshooting HTTP 500: Validate user in memberhsip provider is not called

Azure log has the following error when I try to send a request to a WCF service
In the working case the validate user of the membershipprovider is called, then AfterReceiveRequest is called and finally the webservice is invoked.
But in the non-working case the validateuser is not called. It directly goes on to AfterReceiveRequest and then webservice throws an exception that it can't understand the header.
The azure application gateway routes the request to the VM. It somehow looks the header or membership provider is not being recognized. SSL is managed at the gateway level.
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled ="true" httpsGetEnabled ="true" />
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="IDServices.CustomMembershipProvider,IDServices"/>
</serviceCredentials>
<useRequestHeadersForMetadataAddress />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="endbehavior1">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
{ "timeStamp": "2019-03-11T16:18:29+00:00",
"resourceId": "/SUBSCRIPTIONS/245CA15E-8C11-4F4C-B6D7-9F3E8EC5943F/RESOURCEGROUPS/JXCHANGERG/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/JHAAPPGW",
"operationName": "ApplicationGatewayAccess", "category": "ApplicationGatewayAccessLog", "properties":
{"instanceId":"appgw_0","clientIP":"009.04.06.009","clientPort":"65374","httpMethod":"POST","requestUri":"/PImage.svc","requestQuery":"",
"userAgent":"Apache-HttpClient/4.1.1 (java 1.5)","httpStatus":"500","httpVersion":"HTTP/1.1","receivedBytes":"2638","sentBytes":"917","timeTaken":"0.018","sslEnabled":"on",
"sslCipher":"ECDHE-RSA-AES256-GCM-SHA384","sslProtocol":"TLSv1.2","serverRouted":"40.124.51.221:80","serverStatus":"500","serverResponseLatency":"0.016","host":"jt.inaresecure.com"},
"time": "2019-03-11T16:18:29.0000000Z"}
Can anyone help me with what could be the problem. Is the request failing on the server? All I get is a Security header fault. The code works on every other machine and server except this VM on azure. The request uses the application gateway to route to the VM where the WCF service is hosted on SSL
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode>s:MustUnderstand</faultcode>
<faultstring xml:lang="en-US">The header 'Security' from the namespace 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' was not understood by the recipient of this message, causing the message to not be processed. This error typically indicates that the sender of this message has enabled a communication protocol that the receiver cannot process. Please ensure that the configuration of the client's binding is consistent with the service's binding.</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>
This is the IIS log for the same call probably a different time because of my request
The request is set up to Use SSL. Why does it have 80 in the log? Is it not doing a SSL request? This is a request from SOAP UI
2019-03-11 17:27:44 10.0.0.4 POST /PCServices/2019/MySerivce.svc - 80 - 20.45.4.43 Apache-HttpClient/4.1.1+(java+1.5) - 500 0 0 1468
it may be fails cause of HTTP request.
if you calls from and to HTTPS than authentication done automatically.
but you have to forcefully authenticate while in HTTP request.
if (HttpContext.Current.Request.Url.Scheme.ToUpper().Equals("HTTP"))
{
CustomMembershipProvider auth = new CustomMembershipProvider();
auth.Validate(Username,Pswd);
}

debug OWIN auth middleware

Is there a way to debug OWIN middleware from extensions like WindowsAzureActiveDirectoryBearerAuthenticationOptions and see exactly why the request was rejected (e.g. no token, wrong resource id, invalid signature, …) ?
One thing you can do is enable logging in OWIN:
<configuration>
<system.diagnostics>
<switches>
<add name="Microsoft.Owin" value="Verbose" />
</switches>
</system.diagnostics>
</configuration>
I sent an expired token to my API and got this in the Output:
Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware
Error: 0 : Authentication failed
System.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223:
Lifetime validation failed. The token is expired.
More info about configuring OWIN logging: http://www.tugberkugurlu.com/archive/logging-in-the-owin-world-with-microsoft-owin--introduction.

Biztalk 2010, ADFS and CRM 2011 on premises

I am currently for a client configuring BizTalk 2010 as middleware between Dynamics CRM 2011 on premises with ADFS.
Receiving messages from CRM 2011 to BizTalk is no problem at all.
However the other way around I configured a custom binding as SendPort and can't seem to find the right settings for enforcing HTTPS and authenticating on the ADFS service.
I would imagine that I need settings in the sendport to first authenticate on ADFS and followed on that authenticate against CRM 2011.
Any additional information in regards to this setup and configuration is much appreciated.
Latest sendport information and error:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<client>
<remove contract="BizTalk" name="WcfSendPort_Crm" />
<endpoint address="https://crmurl/XRMServices/2011/Organization.svc" behaviorConfiguration="EndpointBehavior" binding="ws2007FederationHttpBinding" bindingConfiguration="ws2007FederationHttpBinding" contract="BizTalk" name="WcfSendPort_Crm" />
</client>
<behaviors>
<endpointBehaviors>
<remove name="EndpointBehavior" />
<behavior name="EndpointBehavior">
<soapProcessing processMessages="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<ws2007FederationHttpBinding>
<clear />
<binding name="ws2007FederationHttpBinding">
<reliableSession enabled="true" />
<security mode="TransportWithMessageCredential">
<message issuedTokenType="http://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-pr-SAMLTokenProfile-01.html">
<issuer address="https://adfsurl/STS/Active/STS.svc" binding="ws2007HttpBinding" bindingConfiguration="stsBinding">
<identity>
<dns value="STS" />
</identity>
</issuer>
<issuerMetadata address="https://adfsurl/HRGSTS/Active/HRGSTS/mex%22" />
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
Error:
A message sent to adapter "WCF-Custom" on send port "WcfSendPort_Crm" with URI "https://crmurl/XRMServices/2011/Organization.svc" is suspended.
Error details: System.InvalidOperationException: The channel is configured to use interactive initializer 'System.ServiceModel.Security.InfocardInteractiveChannelInitializer', but the channel was Opened without calling DisplayInitializationUI. Call DisplayInitializationUI before calling Open or other methods on this channel.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfInitializationUINotCalled()
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.ICommunicationObject.Open()
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.GetChannel[TChannel](IBaseMessage bizTalkMessage, ChannelFactory`1& cachedFactory)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.SendMessage(IBaseMessage bizTalkMessage)
MessageId: {337CB1AF-1C4A-484A-9CA6-7E0FD3396138}
InstanceID: {FBCDEE5C-8CA2-4C37-87A5-906448C14479}
===
<ws2007HttpBinding>
<clear />
<binding name="ws2007HttpBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None"/>
<message clientCredentialType="UserName"
establishSecurityContext="false"/>
</security>
</binding>
</ws2007HttpBinding>
Assuming that the last snippet you've added is the binding to use when calling the STS and that this is the bit you've added to the machine.config as I have at the time - the binding name should be stsBinding and not ws2007HttpBinding as this should match the name used in the bindingConfiguration attribute of the issuer element in your send port configuration.
The HTTPS would be Binding, CustomBindingElement, allowInsecureTransport = False
For the ADFS you will probably have to use the Ws2007HttpBinding or reproduce the settings of this in your custom bindings probably setting authenticationMode to IssuedToken and for the IssuedTokenParameter, setting the ADFS address in the Issuer address, binding of ws2007HttpBinding and setting up the binding configuration.
See this blog here Calling a service with federated identity from BizTalk Server [2009] – Part I

Azure WCF Service + Sharepoint 2010 Sandbox Visual Web Part = error

I have problem to call Azure WCF Service from sandbox Visual Web Part Sharepoint 2010. All installed al local computer Windows 7 64 Ultimate -
Sharepoint Foundation 2010 to develop web parts and Visual Studio 2010 with Azure SDK. Web Service starting in local Azure Emulator, web part in local computer.
When i use standart master "Add Service Reference" to web part, that generate app.config, then throw error:
ServiceReference1.Service1Client serv = new ServiceReference1.Service1Client();
Label1.Text = serv.GetData(9);
Could not find default endpoint element that references contract 'ServiceReference1.IService1' in the ServiceModel client configuration section.
This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
When i create connection programmatically -
EndpointAddress adr = new EndpointAddress(new Uri("http://127.0.0.1:81/Service1.svc"));
BasicHttpBinding basic = new BasicHttpBinding();
ChannelFactory<ServiceReference1.IService1Channel> fact = new ChannelFactory<ServiceReference1.IService1Channel>(basic, adr);
Label1.Text = fact.CreateChannel().GetData(8);
throw error:
Request for the permission of type "System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089".
app.config webpart:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://127.0.0.1:81/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
web.config Azure WCF Service:
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<!-- To collect diagnostic traces, uncomment the section below or merge with existing system.diagnostics section.
To persist the traces to storage, update the DiagnosticsConnectionString setting with your storage credentials.
To avoid performance degradation, remember to disable tracing on production deployments.
<system.diagnostics>
<sharedListeners>
<add name="AzureLocalStorage" type="WCFServiceWebRole1.AzureLocalStorageTraceListener, WCFServiceWebRole1"/>
</sharedListeners>
<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
</sources>
</system.diagnostics> -->
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
P.S. When all moved to work deployment - Azure и Sharepoint Online - errors again. I create connection programmatically, because read, that in sandbox
solutions app.config not deployed with web part, we must duplicate his code in web.config Sharepoint 2010 - but in Sharepoint Online this file is closed from developers!
I have verified first that you sure can use SharePoint Designer 2010 to create an external content type that consumes and writes data to SQL Server, a Windows Communication Foundation (WCF) Service or a .NET type.
Next SharePoint BCS supports both SOAP and OData however WCF Data Services supports OData services, so to consume a WCF Data Service, you need OData base connectivity. Data view web parts can issue GET requests which works for OData feeds.
SharePoint Online Office 365 supports sandbox solutions which means .Net/C# code and solution deployed web parts are possible however I am not sure if connecting SP Web Parts is possible in the way that you describe because sandbox solutions don't support making outbound web calls.
Have you verified the last part?
You receive correct error from the SharePoint
Request for the permission of type "System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089".
This is because Sandbox restrictions. You can see all permissions which are denied to the sandbox code from this MSDN article. And WebPermission along with SocketPermission which are dinied for code in sandbox solution.
If you want to access external services, does not matter using the TCP or HTTP protocol you should move to the full trust solutions.

Deploying a WCF Data Service/REST Service on IIS 7.5 localhost

Here are the details of my problem. I have one simple WCF Data Service (named WCFServiceAppCBS.svc) using an Entity Framework data access layer that talks to a SqlServer 2008 R2 datasource to return some entities. I just want to expose a few tables as "GET" to be later consumed by external getJSON/AJAX calls in some html files.
For development purposes, it works fine when I'm playing around with it in VS2010 using IIS Express and can consume the OData URI and return data. But, the OData service doesn't return anything when I deploy it to the localhost IIS 7.
All I get is the Atom Pub feed that lists my entities, but when I try to execute any type of iQueryable statements (i.e. http://localhost/WCFServiceAppCBS/OData.svc/officers), I get a generic "the website cannot display the page".
I'm not sure if it is having a problem authenticating or if there are other settings in my Web.Config or IIS that I'm missing.
Here's my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="CBSEntities" connectionString="metadata=res://*/CBSLookup.csdl|res://*/CBSLookup.ssdl|res://*/CBSLookup.msl;provider=System.Data.SqlClient;provider connection string="data source=QCSQL2K8DEV;initial catalog=CBS;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Here's my OData.svc.cs...
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
namespace WCFServiceAppCBS
{
public class OData : DataService<CBSEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
// config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
}
Thanks for any help you can provide!

Resources