Subscription validation error handling - c#

I am currently trying to handle the exception, when a subscription request can't be validated in time, using the Graph SDK. Unfortunately i am not really sure how to achieve this. The exception thrown when a subscription isn't validated in time is:
Microsoft.Graph.ServiceException: Code: InvalidRequest
Message: Subscription validation request failed. Must respond with 200 OK to
this request.
The HttpStatusCode in the ServiceException is "BadRequest" but just this isn't enough to distinguish the error from other common errors since i want to handle them differently. The ServiceException also contains an Error property with a string property called "Code", which contains "InvalidRequest" in my case. The GraphErrorCode enum in the Graph SDK contained this code so i used it with the "IsMatch" method in the ServiceException:
catch (ServiceException serviceException)
{
var invRequest = GraphErrorCode.InvalidRequest.ToString();
if(serviceException.StatusCode == HttpStatusCode.BadRequest)
{
if (serviceException.IsMatch(invRequest))
{
// do something
}
}
}
"InvalidRequest" is defined in the graph documentation as:
The request is malformed or incorrect.
Considering this i still think my ErrorHandling isn't enough to just catch this specific error.
What i want to know is:
Is using the "GraphErrorCode" enum even correct.
Is there a way to handle this specific error without just comparing the exception message ("Subscription validation request failed. Must respond with 200 OK to this request") with a hard coded string.

You're referencing an outdated library (by over 2 years). The correct SDK for this is the Microsoft Graph .NET Client Library. It includes an far more recent error code enumeration.
As for processing the error, the code is typically enough for handling exceptions. The message content is useful for debugging since it often includes more granular information (what exactly failed, which properties were invalid, etc.). My general rule of thumb is to use the code for handling errors but log both code and message properties for debugging.
The import piece to understand is that different endpoints may surface the same error code for different reasons. A BadRequest may mean something different when issuing a GET against a user resource than it does when issuing a POST to /events. Your handler should take into account both the action and the error.
Here is an example error returned when sending an invalid request (/v1.0/me/a):
{
"error": {
"code": "BadRequest",
"message": "Unsupported segment type. ODataQuery: users/48d31887-5fad-4d73-a9f5-3c356e68a038/a",
"innerError": {
"request-id": "fd4c8b27-26af-4b07-a5be-5efb139d1eb7",
"date": "2018-05-22T14:39:02"
}
}
}
If all I handled was the BadRequest, my handler would likely sufficient. I can handle the error and keep the user moving forward. In my log however I store both BadRequest and Unsupported segment type. ODataQuery: users/48d31887-5fad-4d73-a9f5-3c356e68a038/a so that I can properly file a bug in the code.
Another option might be to do some additional parsing. Lets say that /a doesn't always return an error. Maybe /a works fine for AAD accounts but not for MSA users (FTR, /a is entirely fictitious). If this were the case, I might also want to parse the message and see if the BadRequest included "Unsupported segment type" and handle it a bit differently than a BadRequest that didn't include that message.

Related

Error when creating JWT Token

As I am on my way to switch from using the legacy header authentication method to the JWT Token method, I have used the following example found here.
However, I get the following error :
Error calling Login: {
"errorCode": "PARTNER_AUTHENTICATION_FAILED",
"message": "The specified Integrator Key was not found or is disabled. An Integrator key was not specified."
}
Below is my C# code.
string oauthBasePath = "account-d.docusign.com";
string privateKeyFilename = "./private.pem";
int expiresInHours = 1;
ApiClient apiClient = new ApiClient(docuSignUrl);
apiClient.ConfigureJwtAuthorizationFlow(
"IntegratorKey",
"USER ID GUID",
oauthBasePath,
privateKeyFilename,
expiresInHours);
AuthenticationApi authApi = new AuthenticationApi(apiClient.Configuration);
return authApi.Login();
I have found this thread that shows the similar error but it doesn't seem resolved
Update 05/07/2018: I have validated the domain used in my account but I still get the same error message
Update 05/11/2018: When I use my code but that I replace the IntegratorKey, UserID and private key used in the DocuSign Unit Tests here, my code now works !? Hence, I can only conclude that the issue doesn't come from my code but maybe a configuration issue on the DocuSign side ? do I need to configure my Integrator Key a specific way ?
After more investigation, the reason with such an error is that I was not generating the Authorization Code Grant prior to executing my code.
Based on the information found here, I had to perform the following HTTPRequest example :
GET /oauth/auth?
response_type=token
&scope=signature
&client_id=YOUR_INTERGRATOR_KEY
&state=a39fh23hnf23
&redirect_uri=http://www.example.com/callback
Once it is approved, then I can run my code successfully.
In the end, the initial error message is really misleading (I might argue it could be considered a bug ?).

WCF ServiceAuthenticationManager Extensibility

I want to implement my custom security to wcf,I want to use ServiceAuthenticationManager ,but I am confused how it can be block the message.I tried to throw exception but that time I cannot get my exception detail I got just "request error" in rest call and "The caller was not authenticated by the service" in soap calls but I cant get my custom error error message,What is the correct usage of ServiceAuthenticationManager,or where should I block message?
public class MyAuthenticationManager : ServiceAuthenticationManager
{
public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
{
//throw new AuthenticationException("Credentials expired!");
throw new SecurityException("my custom message:Invalid authentication");
return base.Authenticate(authPolicy, listenUri,ref message);
}
}
Authentication/Authorization do not give custom messages. Any kind of indication why you are not authorized or authenticated are a way for an attacker to crack your security or gain information he is not entitled to.
For example saying "Your password is wrong" is an indication that the username exists. That is bad. An unauthorized request should never get such information as a response.
If you want to see what went wrong, write to a log that the server administrator can access. But don't send anything to the client. Ever.
So to summarize: no you cannot get a custom message out and that design is on purpose.

Unable to create Epic using JIRA cloud REST API (C#)?

I am working on a requirement where I need to create an 'Epic' issue type first and then I need to create a 'Bug' issue type mentioning the Epic name in it.
I am parsing the following data for adding an Epic in JIRA but its giving me an error:
string json = #"{""fields"":{""project"":{""key"":""SITBIT""},""summary"": ""Test Epic"",""description"": ""Test Epic Description"",""issuetype"": {""name"":""Epic""}}}";
The above code is giving me the below error:
The remote server returned an error: (400) Bad Request.
The above JSON code is working fine for normal issue type however its throwing an error if I changed the Issue type to 'EPIC'.
What could be the issue? How can I parse the JSON so that the epic can be added.
Secondly, When I am parsing the already added Epic name in the normal issue type then also it gave me (400) bad request error.
Different issue types can have different required fields. To create an epic you also need to specify the 'Epic Name', but this field is missing in your request.
You can use the JIRA REST API to verify which fields are required using the /rest/api/2/issue/createmeta resource:
The fields that can be set on create, in either the fields parameter or the update parameter can be determined using the /rest/api/2/issue/createmeta resource. If a field is not configured to appear on the create screen, then it will not be in the createmeta, and a field validation error will occur if it is submitted.
The JIRA REST API documentation also contains more info about how errors are handled. You only mention the message that corresponds to the status code of the response, but the response body will contain more info, for example:
{
"errorMessages": [
"Field 'priority' is required"
],
"errors": {}
}

OAuth throws null reference exception

Lately the Nemiro.OAuth api is throwing null reference exceptions for some reason. After getting the lates versoin Nemiro.OAuth v1.12.0 and Nemiro.OAuth.loginForms v1.6.0 it started to behave like this, haven't changed my implemented logic in any way.
My file structure in dropbox:
https://www.dropbox.com/home/Apps/MyApplication/MyFolder/SubFolder/Some%20folder1/MyFiles
Old and new uri:
/MyFolder/SubFolder/Some folder1/MyFiles/somefile.png
When I call OAuthUtility.Post it shows following error message:
I'm using following logic to handle the request:
string oldUri = oldPath.ToUri();
string newUri = newPath.ToUri();
var paramCollection = new HttpParameterCollection
{
{"access_token", ACCESS_TOKEN},
{"from_path", oldUri },
{"to_path", newUri },
{"root","auto"}
};
OAuthUtility.Post
(
"https://api.dropboxapi.com/1/fileops/move",
paramCollection
);
I already checked that file exists in dropbox, my access token is valid, also, as you can see the path is correct.. Also it fails for other operations like
https://content.dropboxapi.com/1/files_put/auto{0}/{1}
What could cause this?
Could it be something with new Dropbox api V2?
Update
It actually works, but throws null reference exception at the same time..
That is pretty annoying, that means I need to wrap each operation in try catch block. Also, when I created new console application and executed the same code, it worked without any exceptions. Which means, something is wrong in my project.
0. Dropbox API v1 has been deprecated:
https://blogs.dropbox.com/developers/2016/06/api-v1-deprecated/
...In order to provide our developers with the most up-to-date features and support a single, consistent platform, we’ll be turning off API v1 a year from now, on 6/28/2017.
It remains approximately two months :-) I recommend switching to the new version of the API.
1. Do you pass the URI? But why are you doing this? Just use a string path relative to the root directory of the application. I tried to use a URI, this code does not work for me, the server returns an error 404.
I used relative paths and checked the code and do not see any problems.
If possible, show the full code in which the problem occurs.
Or you can send the project to me by email: aleksey.nemirogmail.com

Determining meaningful HTTP response codes in RESTful API for business rule validation

I'm currently in the early stages of building a RESTful API and have been going back and forth on the correct way to handle business rule validation.
I am using Web API 2 and currently use IValidatableObject to handle validating the model. If, for example, a required field is missing, I am returning "400 Bad Request" and the ModelState.
I began to add business rule validation to IValidatableObject's Public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) method and continued to return "400 Bad Request" with a message describing the business rule that didn't pass validation. Then I took a step back and thought "Business rules are different from model validation, the request is perfectly valid, and I should not be returning 400."
Now I plan on moving the business rule validation out of model validation and into domain logic. This has left me thinking about how I should return not only the correct status code but how the client will determine the proper message to display.
I'm torn between 403 Forbidden and 422 Unprocessable Entity, leaning toward 422. Any suggestions welcome.
Now let us say that I make a request that fails multiple business rules, and I return a 422 and a collection of error messages. I want the client to be able to understand the error and present the message how they see fit, not just display the message in my response.
Which HTTP status code is most appropriate for failed business?
What is the best practice around returning error messages?
Is it acceptable to return 422.x and document each .x, so the client knows what to do? That seems to leave me with the limitation of only returning one error per request.
Should I define Error codes and return them with the error message? For example:
{
"Errors": [
{ "Error": { "Code": "E0001", "Message": "You failed business rule 1" } },
{ "Error": { "Code": "E0002", "Message": "You failed business rule 2" } }
]
}
Any feedback would be awesome! Thanks!
Take a look at this answer here
I wouldn't send a 403 because your case has nothing to do with authorization.
I would send 400 if your model came back as null. i.e the model binder doesn't know what to do with what you posted.
Send the status as 422 with the errors as content.

Categories

Resources