Stuck on this OpenIddict issue while validation with client creadentials token - c#

System.InvalidOperationException: An identity cannot be extracted from this request.
This generally indicates that the OpenIddict server stack was asked to validate a token for an endpoint it doesn't manage.
To validate tokens received by custom API endpoints, the OpenIddict validation handler (e.g OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme or OpenIddictValidationOwinDefaults.AuthenticationType) must be used instead.
at OpenIddict.Server.OpenIddictServerHandlers.ValidateAuthenticationDemand.HandleAsync(ProcessAuthenticationContext context)
at OpenIddict.Server.OpenIddictServerDispatcher.DispatchAsync[TContext](TContext context)
at OpenIddict.Server.OpenIddictServerDispatcher.DispatchAsync[TContext](TContext context)
at OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator.AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
Accept: */*
Host: localhost:7174
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
:method: GET
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IlYyUERaNl9RUjRfNFo0Q1VMUkUwWFdRRU1KNFVDT0VGSjNDQldTQUQiLCJ0eXAiOiJhdCtqd3QifQ.eyJzdWIiOiJwb3N0bWFuIiwic29tZS1jbGFpbSI6InNvbWUtdmFsdWUiLCJvaV9wcnN0IjoicG9zdG1hbiIsImNsaWVudF9pZCI6InBvc3RtYW4iLCJvaV90a25faWQiOiI3NGE3ZGNlMC1kNjJkLTRmZjQtYjg1MS1kMjRjN2E1OGIwNTEiLCJzY29wZSI6ImFwaSIsImV4cCI6MTY3MjIxMjQzMywiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NzE3NC8iLCJpYXQiOjE2NzIyMDg4MzN9.bls8ceNA9bU-xr1-9huV4LDqifX7KDn8E1bqGPGeeWh9ePeN1mYnywFC6lPVls8OtCmtm1v9iTnnfaoZ3r2v_IoKahl727B4QD8AkKpy_8ExiBBECtX9HqDid3w0c8dYS1Rka2xyh5mcKJzlqNlSucNbRqj7Hu8wisizV89K45qmWBsZTIsBqJOR5DKDjVzAEmAvjccD8Hb9kjF6lSiis2E7x41YO0dB4ugc5gEm1huEI44bps7qj9V2mQ70EcNi74KgK3Y57JsityV1Oqjv14gour2jjvccATtLhOtNisUfbw10jPlRj3AT1XiHDjjIhR5pb0z6XTJRblpmNt8wNQ
Referer: https://localhost:7174/swagger/index.html
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty
Does anyone know about this? Please tell me the solution

Related

CreatedAtRoute: No route matches with empty route values

I'm currently struggling with CreatedAtRoute, below are the details.
Desired solution in the future
Return object and URI in location header linking to endpoint GetGlobalSettings.
Current situation and problem
I have the following POST endpoint for resource creation which returns CreatedAtRoute like this return CreatedAtRoute(nameof(GetGlobalSettings), result.Data);
The route set in the location header should link to the endpoint with this method head:
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<GlobalSettingDto>> GetGlobalSettings()
With this I always get the following exception:
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtRouteResult.OnFormatting(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)
at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Content-Type: application/json
:authority: localhost:5001
:method: POST
:path: /api/v1/GlobalSettings
:scheme: https
Accept: text/plain
Accept-Encoding: gzip, deflate, br
Accept-Language: de,de-DE;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Host: localhost:5001
Referer: https://localhost:5001/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48
DNT: 1
Origin: https://localhost:5001
Content-Length: 768
sec-ch-ua: " Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty
I have API-versioning active, so I also tried the CreatedAtRoute-call like this:
var routeValues = new { version = "1.0" };
return CreatedAtRoute(nameof(GetGlobalSettings), routeValues, result.Data);
But this still throws the same error.
In your case, you should use CreatedAtAction:
return CreatedAtAction(nameof(GetGlobalSettings), routeValues, result.Data);
Regarding the difference between CreatedAtAction and CreatedAtRoute, you can see this thread.

How can i make a multipart/form-data request with string

I'm trying to make a request on this site: https://textitor.com/ to create pastes but I saw that the content-type was multipart/form-data.
I saw on Stackoverflow several explanations to make a multipart/form-data request with a file but I couldn't find how to do it with strings.
So I'm hoping that someone will be able to help me
You can see below Request Header & Parameter:
Host: api.textitor.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0
Accept: application/json, text/plain, */*
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
Content-Type: multipart/form-data; boundary=---------------------------224061383921529899882446413168
Content-Length: 797
Origin: https://textitor.com
Connection: keep-alive
Referer: https://textitor.com/
TE: Trailers
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="pastetitle"
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="pastetext"
testafefafafaaf
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="expirationtime"
never
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="viewlimit"
unlimited
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="syntaxlang"
none
-----------------------------224061383921529899882446413168
Content-Disposition: form-data; name="ispublic"
false
-----------------------------224061383921529899882446413168--

POST http request C# - Request Payload

I'm trying to POST HTTP request on C# .NET app, i need some help
because i have no idea if that is possible using the request data from google chrome developer tools.
General :
Request URL: https://my.domain.ae/data/verify/Proc
Request Method: POST
Status Code: 200
Remote Address: ip:443
Request Payload :
------WebKitFormBoundaryWVKBQMeG4O3GcfXR
Content-Disposition: form-data; name="Id"
016
------WebKitFormBoundaryWVKBQMeG4O3GcfXR
Content-Disposition: form-data; name="Lvl"
10
------WebKitFormBoundaryWVKBQMeG4O3GcfXR
Content-Disposition: form-data; name="Name"
Test
------WebKitFormBoundaryWVKBQMeG4O3GcfXR
Content-Disposition: form-data; name="Score"
23
------WebKitFormBoundaryWVKBQMeG4O3GcfXR
Content-Disposition: form-data; name="Coins"
100
------WebKitFormBoundaryWVKBQMeG4O3GcfXR--
Request Headers :
:authority: my.domain.ae
:method: POST
:path: /data/verify/Proc
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 617
content-type: multipart/form-data; boundary=----WebKitFormBoundaryWVKBQMeG4O3GcfXR
cookie: user_language=ar; ****
origin: https://my.domain.ae
referer: https://my.domain.ae/index
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
x-requested-with: XMLHttpRequest

Enable CORS in Azure Mobile Services - OPTIONS not authorized

I am creating .Net web services using Azure Mobile Services. The services themselves work fine, but I want to enable CORS.
My Global.asax contains:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Authorization, Origin, Content-Type, Accept, X-Requested-With,x-zumo-application,x-zumo-installation-id");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
My WebAPIConfig.cs contains:
public static void Register()
{
ConfigOptions options = new ConfigOptions();
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
var cors = new EnableCorsAttribute("*", "*", "*","*");
config.EnableCors(cors);
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
}
My request/response:
OPTIONS http://********.azure-mobile.net/API/MyLogin?username=username&password=password&email=testtest%40example.com&_=140191793307 HTTP/1.1
Host: ********.azure-mobile.net
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: null
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type,x-zumo-application,x-zumo-installation-id
Connection: keep-alive
Cache-Control: max-age=0
HTTP/1.1 401 Unauthorized
Content-Length: 81
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/8.0
WWW-Authenticate: Basic realm="Service"
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=50b9234b61ec5f663e817ec57c430ca7b921bbcd842719dfc2bdc27374adea87;Path=/;Domain=********.azure-mobile.net
Date: Wed, 04 Jun 2014 21:38:56 GMT
<Error><Message>Authorization has been denied for this request.</Message></Error>
There is a workaround for enabling CORS in Mobile Services here:
https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8
You don't need the Application_BeginRequest part -- requests/responses don't go through that code path -- they go through the OWIN pipeline. Good thing is that you only need the gist above to get going.
Hope this helps!
Henrik

Cannot Return Custom HTTP Error Details Remotely

This is a strange one. I'm running MVC 3 and have a custom action result that wraps exceptions and returns a message along with the standard HTTP error.
public class ExceptionResult : ActionResult
{
private readonly Exception _exception;
public ExceptionResult(Exception exception)
{
_exception = exception;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ClearHeaders();
response.Cache.SetNoStore();
response.ContentType = ContentType.Json;
var baseEx = _exception as BaseException ?? new ServerException(_exception);
var result = baseEx.GetResult();
var json = result.ToJSON();
response.Write(json);
response.StatusCode = (int)result.Status.Code;
}
}
When I run this locally I get exactly what I expect:
HTTP/1.1 400 Bad Request
Cache-Control: no-store
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Thu, 01 Dec 2011 19:00:03 GMT
Content-Length: 81
{"error":"invalid_request","error_description":"Parameter grant_type is missing"}
But when I try to connect from a different machine I get the standard IIS error message instead:
HTTP/1.1 400 Bad Request
Cache-Control: no-store
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Thu, 01 Dec 2011 19:02:33 GMT
Content-Length: 11
Bad Request
UPDATE
There must be some http module somewhere in the IIS pipeline that is swallowing the response and rewriting the content. I wrote a module to log the request and response and it's returning exactly what I expect however what actually makes it to the browser is wrong.
2011-12-02 15:39:00,518 - ======== Request ========
2011-12-02 15:39:00,518 - GET /oauth/2/token HTTP/1.1
2011-12-02 15:39:00,519 - Cache-Control: max-age=0
2011-12-02 15:39:00,519 - Connection: keep-alive
2011-12-02 15:39:00,519 - Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
2011-12-02 15:39:00,519 - Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
2011-12-02 15:39:00,519 - Accept-Encoding: gzip,deflate,sdch
2011-12-02 15:39:00,519 - Accept-Language: en-US,en;q=0.8
2011-12-02 15:39:00,519 - Host: micah-pc:8095
2011-12-02 15:39:00,519 - User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2
2011-12-02 15:39:00,519 - =========================
2011-12-02 15:39:00,519 - OAuth exception occurred.
BoomTown.OAuth.OAuthException: Parameter grant_type is missing
at BoomTown.OAuth.Request.TokenRequest.GetRequestValidator() in C:\code\BoomTown\Api\BoomTown.OAuth\Request\TokenRequest.cs:line 19
at BoomTown.OAuth.Request.OAuthRequestBase.Validate() in C:\code\BoomTown\Api\BoomTown.OAuth\Request\OAuthRequestBase.cs:line 33
at BoomTown.OAuth.Request.OAuthRequestBase..ctor(HttpRequestBase request, IOAuthServiceLocator serviceLocator) in C:\code\BoomTown\Api\BoomTown.OAuth\Request\OAuthRequestBase.cs:line 28
at BoomTown.OAuth.Request.TokenRequest..ctor(HttpRequestBase request, IOAuthServiceLocator serviceLocator) in C:\code\BoomTown\Api\BoomTown.OAuth\Request\TokenRequest.cs:line 13
at BoomTown.Api.Web.Controllers.OAuth.V2.OAuthController.Token() in C:\code\BoomTown\Api\BoomTown.Api.Web\Controllers\OAuth\V2\OAuthController.cs:line 26
2011-12-02 15:39:00,520 - ======= Response =======
2011-12-02 15:39:00,520 - HTTP/1.1 400 Bad Request
2011-12-02 15:39:00,520 - Cache-Control: no-store
2011-12-02 15:39:00,520 - X-AspNet-Version: 4.0.30319
2011-12-02 15:39:00,520 - Content-Type: application/json; charset=utf-8
2011-12-02 15:39:00,520 - {"error":"invalid_request","error_description":"Parameter grant_type is missing"}
SOLUTION
Thanks to a little sleuthing I was able to figure it out. I setup IIS tracing which confirmed my suspicions that it was related to the customerrormodule which was intercepting my requests and overwriting my error messages. I kept monkeying with the
<system.web>
<customErrors />
<system.web>
settings but to no avail. I was on the right track, but since it's IIS 7 that I'm running I needed to change the correct web.config section like this:
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
Now all my custom JSON messages come through perfectly. Big thanks to Jason Finneyfrock for the tag team on this one.
In your web.config, do you have httpErrors defined to only be DetailedLocalOnly? I'm not sure whether or not the content would be removed in this situation.
http://www.iis.net/ConfigReference/system.webServer/httpErrors
I came across this, not sure if it will help:
context.HttpContext.Response.TrySkipIisCustomErrors = true;

Categories

Resources