ServiceAuthorizationManager exception always sending xml response - asp.net-mvc

I have a custom ServiceAuthorizationManager implemented in wcf webhttp service to do api key verification. It sends a webfaultexception with the code 403 if the key is invalid.
But the issue is, when the exception is thrown, it s always send to the client as xml.
The service accepts both JSON and XML and it s working fine for all the other operations except for the exception from the manager.
No matter if I set the accept header or content type the result is always xml. But for other requests, the response type switches perfectly according to the content-type header
Here's the web.config
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
Any help is really appriciated.

If anyone else ran into this issue: looks like no way to fix it. The solution I did was to do the verification in the service's constructor. Make sure the instance context mode is set to per call.
More info http://amilagm.com/2012/04/better-way-to-do-api-key-verification-in-wcf-webhttp-services/

Related

Swashbuckle refuses to show response example for HTTP 500

I'm using Swashbuckle for a web api app in .Net Core 3.1. I want response examples for various response codes. I can get all of them working except HTTP 500. These are the attributes on the a particular method:
[SwaggerRequestExample(typeof(GroupInfoRequest), typeof(GroupInfoRequestExample))]
[SwaggerResponseExample(Status200OK, typeof(GroupInfo200Example))]
[SwaggerResponseExample(Status400BadRequest, typeof(GroupInfo400Example))]
[SwaggerResponseExample(Status403Forbidden, typeof(GroupInfo403Example))]
[SwaggerResponseExample(Status404NotFound, typeof(GroupInfo404Example))]
[SwaggerResponseExample(Status500InternalServerError, typeof(GroupInfo500Example))]
[ProducesResponseType(Status200OK)]
[ProducesResponseType(Status400BadRequest)]
[ProducesResponseType(Status403Forbidden)]
[ProducesResponseType(Status404NotFound)]
[ProducesResponseType(Status500InternalServerError)]
I can get all of them to render except the GroupInfo500Example. The application only returns an HTTP 500 to indicate an internal exception that isn't caught by other exception handlers. It is intended to return a body that contains, among other things, a GUID that can be passed in to our support organization to help them look up the exception in the application logs. I can not get the example to render for any 5xx error. If I change it to another status code, it renders, so it's specifically the 5xx result that doesn't render. I've checked the openapi json produced and it's not produced as part of the generated JSON. Is there a filter in place that keeps 5xx response docs from showing response examples?
Finally figured it out. I was missing part of the 'ProducesResponseType' attribute. It needs to have the return type as well as the HTTP status code. This works:
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status200OK)]
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status400BadRequest)]
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status403Forbidden)]
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status404NotFound)]
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status422UnprocessableEntity)]
[ProducesResponseType(typeof(ADServiceOperationMultipleResult<GroupActionRequestForUsers, UserQuery>), Status500InternalServerError)]
Oddly enough, some status codes were including the example without it, but now the examples appear consistently as long as I include the method return type in the attribute.

Are all elements in a POST requests body mandatory?

If a POST request requires that i send four data elements in the body, like:
{
"name":abc,
"surname":xyz,
"contact_no":1234,
"address":random_value
}
What will happen if I miss out some of the elements, for example if I call the web service with elements like,
{
"name":abc,
"surname":xyz,
}
What error is the server likely to throw ? I am having this issue because I am making a API call and it's giving me a HTTP error 500, so I guess it's not an error on my part, but this is one doubt i wanted to clear. Thanks in advance.
Its depends on the service structure (if all fields are mandatory or not),
and HTTP error (500) returns to server error or (server or link) not found .

Thinktecture.Identity SAML token unauthorized

I am using the Thinktecture.IdentityModel 4.0 samples for WebApiSecurity. I've modified the AdfsSamlClient to use our ADFS Server. I am able to get a SAML token from out ADFS Server using
var channel = factory.CreateChannel();
var token = channel.Issue(rst) as GenericXmlSecurityToken;
Then I try to make the service call
var client = new HttpClient { BaseAddress = _baseAddress };
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("AdfsSaml", saml);
var response = client.GetAsync("identity").Result;
And get a 401 - Not Authorized call.
I am not sure how to debug this. I have tracing for Microsoft.IdentityModel, but it is only information level trace, no errors or warnings, and nothing I am able to use to debug.
The interesting part of the service trace:
1.
Description OnEndRequest is redirection to IdentityProvider '/WebHost/api/identity'
2.
Description CreateSignInRequest
BaseUri https://[ADFS...]/adfs/ls/
wa wsignin1.0
wtrealm https://[WorkStation...]/WebHost/
wctx rm=0&id=passive&ru=%2fWebHost%2fapi%2fidentity
3.
Description Redirecting to IdentityProvider: 'https://[ADFS...]/adfs/ls/?wa=wsignin1.0&wtrealm=https%3a%2f%2f[WorkStation...]%2fWebHost%2f&wctx=rm%3d0%26id%3dpassive%26ru%3d%252fWebHost%252fapi%252fidentity&wct=2013-09-30T17%3a35%3a04Z'
Thanks for any insight.
Main thing that springs to mind is to make sure the server knows how to handle the "AdfsSaml" scheme that you're using, so you'll want to make sure that your mapping is correct to your token handler.
One thing I tried was to create my own token handler, and mapped that as the token handler for the header. If you want, you can start with Thinktecture's own HttpSamlSecurityTokenHandler, and debug your way through that. Obviously, if it never hits it, then you've got a mapping issue somewhere.
I also found that if an exception was thrown in the ClaimsAuthenticationManager, it would report as unauthorized - even though the exception being thrown was something completely unrelated (in my case, an InvalidCastException). That stumped me for a while, because I hadn't realise that authentication had gotten so far down the pipeline and that validation of the token had actually been successful - I was just checking the HTTP response, which kept saying unauthorised - so make sure you're not being misled by anything trivial like that.

Fault calling SAP web service with generated SUDZC proxy: CX_ST_MATCH_ELEMENT

Trying to call a SAP SOAP Web Service from a generated sudzc app shows errors I don't know:
SudzCExamples[5192:f803] <?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:sap-
com:document:sap:soap:functions:mc-style"><soap:Body><ZComUrlGetrecords>
<IYear>2012</IYear></ZComUrlGetrecords></soap:Body></soap:Envelope>
SudzCExamples[5192:f803] <soap-env:Envelope xmlns:soap-
env="http://schemas.xmlsoap.org/soap/envelope/"><soap-env:Header></soap-env:Header><soap-
env:Body><soap-env:Fault><faultcode>soap-env:Server</faultcode><faultstring
xml:lang="en">CX_ST_MATCH_ELEMENT:XSLT exception.System expected element
'IYear'</faultstring><detail><ns:SystemFault
xmlns:ns="http://www.sap.com/webas/710/soap/runtime/abap/fault/system/">
<Host>undefined</Host><Component>APPL</Component><ChainedException>
<Exception_Name>CX_SOAP_CORE</Exception_Name><Exception_Text>CX_ST_MATCH_ELEMENT:XSLT
exception.System expected element 'IYear'</Exception_Text></ChainedException>
<ChainedException><Exception_Name>CX_SXMLP</Exception_Name><Exception_Text>XSLT
exception</Exception_Text></ChainedException><ChainedException>
<Exception_Name>CX_ST_MATCH_ELEMENT</Exception_Name><Exception_Text>System expected
element 'IYear': Main Program:/1BCDWB/WSS825E06E4DEC40F9171D|
Program:/1BCDWB/WSS825E06E4DEC40F9171D| Line: 18| Valid:X</Exception_Text>
</ChainedException></ns:SystemFault></detail></soap-env:Fault></soap-env:Body></soap-
env:Envelope>
2012-03-11 20:09:30.631 SudzCExamples[5192:f803] soap-env:Server CX_ST_MATCH_ELEMENT:XSLT
exception.System expected element 'IYear'
(null)
The strange thing is that it seems as if the request has the IYear element. Can someone tell me where to search the problem?
I ran into this same problem yesterday and discovered the solution after some experimentation. First thing I did was use my SoapUI client to make the request successfully. SoapUI comes with a free trial and even if you do not use the free trial you can still use it to make accesses to the web service without registering it. I used the xml from the successful request I made to compare against the request that SudzC was making. They differ in several ways, and the way that SudzC forms the request is not sufficient.
My suggestion to you is to compare the two requests and change SudzC's request to match the SoapUI request. You can do this by editing the Soap source code that SudzC gives to you, this source code is found particularly in the Soap.m file in the createEnvelope function.
Also, if your requests have an empty header SudzC does not include the header part of the request. Hard code in an empty header after the namespace portion of the envelope. Doing all this fixed this exact issue for me.

Supporting the "Expect: 100-continue" header with ASP.NET MVC

I'm implementing a REST API using ASP.NET MVC, and a little stumbling block has come up in the form of the Expect: 100-continue request header for requests with a post body.
RFC 2616 states that:
Upon receiving a request which
includes an Expect request-header
field with the "100-continue" expectation, an origin server MUST
either respond with 100 (Continue) status and continue to read
from the input stream, or respond with a final status code. The
origin server MUST NOT wait for the request body before sending
the 100 (Continue) response. If it responds with a final status
code, it MAY close the transport connection or it MAY continue
to read and discard the rest of the request. It MUST NOT
perform the requested method if it returns a final status code.
This sounds to me like I need to make two responses to the request, i.e. it needs to immediately send a HTTP 100 Continue response, and then continue reading from the original request stream (i.e. HttpContext.Request.InputStream) without ending the request, and then finally sending the resultant status code (for the sake of argument, lets say it's a 204 No Content result).
So, questions are:
Am I reading the specification right, that I need to make two responses to a request?
How can this be done in ASP.NET MVC?
w.r.t. (2) I have tried using the following code before proceeding to read the input stream...
HttpContext.Response.StatusCode = 100;
HttpContext.Response.Flush();
HttpContext.Response.Clear();
...but when I try to set the final 204 status code I get the error:
System.Web.HttpException: Server cannot set status after HTTP headers have been sent.
The .NET framework by default always sends the expect: 100-continue header for every HTTP 1.1 post. This behavior can be programmatically controlled per request via the System.Net.ServicePoint.Expect100Continue property like so:
HttpWebRequest httpReq = GetHttpWebRequestForPost();
httpReq.ServicePoint.Expect100Continue = false;
It can also be globally controlled programmatically:
System.Net.ServicePointManager.Expect100Continue = false;
...or globally through configuration:
<system.net>
<settings>
<servicePointManager expect100Continue="false"/>
</settings>
</system.net>
Thank you Lance Olson and Phil Haack for this info.
100-continue should be handled by IIS. Is there a reason why you want to do this explicitly?
IIS handles the 100.
That said, no it's not two responses. In HTTP, when the Expect: 100-continue comes in as part of the message headers, the client should be waiting until it receives the response before sending the content.
Because of the way asp.net is architected, you have little control over the output stream. Any data that gets written to the stream is automatically put in a 200 response with chunked encoding whenever you flush, be it that you're in buffered mode or not.
Sadly all this stuff is hidden away in internal methods all over the place, and the result is that if you rely on asp.net, as does MVC, you're pretty much unable to bypass it.
Wait till you try and access the input stream in a non-buffered way. A whole load of pain.
Seb

Resources