How do I workaround a false positive: MetadataAddress or Authority must use HTTPS --> RequireHttpsMetadata=false - asp.net-core-webapi

I have a web.api (.Net 6) which has been working perfectly. I got a new computer, installed VS, postman, etc. and when I hit my API I get this error (see below).
But when I use my old computer everything works perfectly.
Can anyone think of anything as to why I would experience this behavior?
Error:
System.InvalidOperationException: The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerPostConfigureOptions.PostConfigure(String name, JwtBearerOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass10_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at System.Lazy`1.get_Value()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme)
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 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: */*
Connection: keep-alive
Host: localhost:57877
User-Agent: PostmanRuntime/7.29.2
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjBoWk5vLXZJSkt0WENYeEdWbTk3VmhMcmd0UjFvMzZjZE5ZVk54dk82Z0UifQ.eyJpc3MiOiJodHRwczovL2FjdWl0eWJyYW5kc2RldmxvZ2luLmIyY2xvZ2luLmNvbS84ZTE5OWEwZS05ZGI3LTRiZjUtOWJlNi1kZTUzYzg0N2M1YjUvdjIuMC8iLCJleHAiOjE2Njc2NzEyMzIsIm5iZiI6MTY2NzU4NDgzMiwiYXVkIjoiZDY1YTc5OTMtMDcwMC00MTI0LWI1NGEtMmE2ZWIwNTNhMjI0Iiwic3ViIjoiM2E4ZWYwMjgtZDcyNS00MmZlLTgxMDItYWM4NzhjODQ3MmJjIiwiZ2l2ZW5fbmFtZSI6IlJvYmVydCIsImZhbWlseV9uYW1lIjoiR3JlZW4iLCJzaWduSW5OYW1lIjoiUlhHMThAYWN1aXR5c3NvLmNvbSIsInNjcCI6ImNkbWRhdGEud3JpdGUgY2RtZGF0YS5yZWFkIiwiYXpwIjoiNDE2MjVlMzMtMTk1Ni00ZjM2LTgwNGItYTkxOTI0NDVkZGJhIiwidmVyIjoiMS4wIiwiaWF0IjoxNjY3NTg0ODMyfQ.mJ4rmtIp3IwqS2e56ON27pDPeBbNW9MYNp7fUpqRtVaSrVa2Ija0mwo8f2XNMaC0FUs2rvjs2wRn7vF1FmhI8-hM9RsC8po1tYkg1QtmOWbpF6SpUZZapyE1QXIRvyfW1InLP7abzCCu0_JHLHx8wXlCYUXYrHtIGBa27fe5jo1LIZXnGl0Ok6aYLBPxsdiryQJaI4VLNp0157PVfr1shayrjjkZ3P67XbbKfMzzspjXNe-ZCbo0lDlwm-PsOEdTlNisRiDpzAYrvdr8yG5IlS9uqVWTHLUH0zhBPQNgYr8relFRiGqjqFt9DKpms9B24P4rI47A6aupgyNYxJFo-g
Content-Type: application/json
Content-Length: 3872
Ocp-Apim-Subscription-Key: d81e91544c174a7c807a7a9f6c5a82d5
Postman-Token: bd3ae0bd-8d5b-44f4-bc49-296140d09300

Related

Error Ocelot Gateway .Net Core 6 , Puscblish in IIS local

I'm trying to publish my API Gateway in IIS locally however, they always show me error 502 (bad gateway), I can't find the problem, please help me to know which way I should go.
{
"Routes": [
{
"UpstreamPathTemplate": "/gateway/seguridad/auth",
"UpstreamHttpMethod": [ "POST" ],
"DownstreamPathTemplate": "/api/auth",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7221
}
]
},
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:8085"
}
}
my endpoint is working correctly in a POST method, both in debug and publication.
I am consulting the url:
https://localhost:8085/gateway/seguridad/auth
The error it shows when trying to run the endpoint is 502 (bad gateway) and in the system event viewer, it is the following.
Category: Ocelot.Responder.Middleware.ResponderMiddleware
EventId: 0
SpanId: ce42c03504779a7b
TraceId: c20b3aaf91fe3ccac5d82b8b00b385ae
ParentId: 0000000000000000
RequestId: 40000014-0002-fb00-b63f-84710c7967bb
RequestPath: /gateway/seguridad/auth
requestId: 40000014-0002-fb00-b63f-84710c7967bb, previousRequestId: no previous request id, message: Error Code: ConnectionToDownstreamServiceError Message: Error connecting to downstream service, exception: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.CompleteHandshake(SslAuthenticationOptions sslAuthenticationOptions)
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Ocelot.Requester.HttpClientHttpRequester.GetResponse(HttpContext httpContext) errors found in ResponderMiddleware. Setting error response for request path:/gateway/seguridad/auth, request method: POST
The Error : "The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot" probably means that your self signed certificate is not trusted by your computer.
Does the service running on "localhost:7221" have a SSL certificate installed? If you visit it in your browser, you can figure which certificate you need to install.
Have a look at C# Ignore certificate errors?
For a work around while developing, you can add this to your program:
ServicePointManager.ServerCertificateValidationCallback += sender, cert, chain, sslPolicyErrors) => true;
However, I would not recommend doing this for production systems. Also if you are hosting on shared servers - I would keep your downstream servers on https

Update from .NET Core 2.1 to .NET Core 3.1: Using Terraform 0.12.31 to build out the AWS Resources: AWS IoT Publish now throws SSL Error

I am doing an upgrade from .NET Core 2.1 to .NET Core 3.1.
I have upgraded my projects to use .NET Core 3.1. I am using the AWS IoT package described below
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.4.0" />
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.Json" Version="2.0.0" />
<PackageReference Include="AWSSDK.ApiGatewayManagementApi" Version="3.7.0.96" />
<PackageReference Include="AWSSDK.CognitoIdentityProvider" Version="3.7.1.68" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.0.97" />
<PackageReference Include="AWSSDK.IoT" Version="3.7.6.28" />
<PackageReference Include="AWSSDK.S3" Version="3.7.4.3" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="6.15.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.15.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
</ItemGroup>
</Project>
Now, when I use the AWS IoT package to publish a message I log this SSL Error
ERROR: Exception: Type: System.Net.Http.HttpRequestException Message: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Security.SslStream.ThrowIfExceptional()
at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
at System.Net.Security.SslStream.<>c.b__65_1(IAsyncResult iar)
at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) at Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
at Jobs.Function.PostJobDiscussion(APIGatewayProxyRequest apiGatewayProxyRequest, ILambdaContext context) in /codebuild/output/src782906800/src/api/Jobs/src/Jobs/PostJobDiscussion.cs:line 98
I am using a Cloudfront distribution and I redirect my app to HTTPS for this Post api call.
I am building out these AWS resources using Terraform 0.12.31
My cloud front distribution uses an s3 bucket configuration for Terraform is described below
resource "aws_cloudfront_distribution" "s3_distribution" {
origin {
domain_name = aws_s3_bucket.webapp_s3.bucket_regional_domain_name
origin_id = "S3-${var.account_alias}-${var.domain_name}"
s3_origin_config {
origin_access_identity = aws_cloudfront_origin_access_identity.portal_cdn_oai.cloudfront_access_identity_path
}
}
enabled = true
is_ipv6_enabled = true
comment = ""
default_root_object = "index.html"
// setup a custom error to default to the index.html for the spa
custom_error_response {
error_caching_min_ttl = 300
error_code = "404"
response_code = "200"
response_page_path = "/index.html"
}
aliases = [var.cdn_domain_name]
.....
viewer_certificate {
cloudfront_default_certificate = false
acm_certificate_arn = data.aws_acm_certificate.portal_cert.arn
minimum_protocol_version = "TLSv1.1_2016"
ssl_support_method = "sni-only"
}
}
I have checked that my certificates in AWS are valid meaning they are not expired but the error says
The remote certificate is invalid according to the validation procedure.
Somehow the SSL/TLS handshake is not working
After my upgrade to .NET 3.1 any lambda that is using AWS IoT Publish is failing.
In the browser, the response headers
The Response Headers
content-length: 41
content-type: application/json
date: Wed, 08 Dec 2021 16:55:04 GMT
via: 1.1 2d64784a9c03401d2f7f505cbef3c986.cloudfront.net (CloudFront)
x-amz-apigw-id: KChz0HFCIAMFeWw=
x-amz-cf-id: YSrTkIkUyMZY3wiT91WcmFDivk_0cmwlEUE0OeQtD3wGUREz4pXf7Q==
x-amz-cf-pop: IAH50-C2
x-amzn-errortype: InternalServerErrorException
x-amzn-requestid: a00f8e86-de54-44d4-8595-b87a50c04a4b
x-cache: Error from cloudfront
The Request Headers
:authority: api.dev2.project-caisson.com
:method: POST
:path: /jobs/c9b8d1d2-b68c-45d1-9fde-27fa8cc358dd/discussion
:scheme: https
accept: application/json, text/plain, /
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: jwt token
content-length: 129
content-type: application/json
origin: http://localhost:4200
referer: http://localhost:4200/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
The Signnature algorithm for the certificate is SHA256WITHRSA
The policy on my lambda for IoT is
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect",
"iot:Publish",
"iot:Subscribe",
"iot:Receive",
"iot:GetThingShadow",
"iot:UpdateThingShadow",
"iot:DeleteThingShadow"
],
"Resource": "*"
}
]
}
These certs have not changed since the upgrade. I have viewed the certs using openssl command and everything looks fine.
The code in C# that triggers the error is
using (var iotDataClient = CreateAmazonIotDataClient())
{
var mqttBrokerEndpoint = Environment.GetEnvironmentVariable("MQTTBroker");
context.Logger.LogLine($"Created an AmazonIotDataClient: MQTT Env Variable {mqttBrokerEndpoint}");
var serviceURL = iotDataClient.Config.ServiceURL;
context.Logger.LogLine($"AmazonIotDataClient: ServiceURL {serviceURL}");
context.Logger.LogLine($"iotDataClient Config: ProxyHost {iotDataClient.Config.ProxyHost}");
context.Logger.LogLine($"iotDataClient Config: ProxyPort {iotDataClient.Config.ProxyPort}");
context.Logger.LogLine($"iotDataClient Config: AllowAutoRedirect {iotDataClient.Config.AllowAutoRedirect}");
context.Logger.LogLine($"iotDataClient Config: AuthenticationServiceName {iotDataClient.Config.AuthenticationServiceName}");
context.Logger.LogLine($"iotDataClient Config: Url {iotDataClient.Config.DetermineServiceURL()}");
//iotDataClient.Config.Validate();
// There are three levels of QoS: 0 - at most once. 1 - at least once. 2 - exactly once.
await iotDataClient.PublishAsync(new PublishRequest
{
Topic = $"{latestMessageFromMTT.ClientID}/JobDiscussion",
Qos = 1,
Payload = new MemoryStream(
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jobDiscussion)))
}, cancellationTokenSource.Token);
}
With the CreateAmazonIotDataClient()
if (_iotDataClient != null) return _iotDataClient;
var mqttBrokerEndpoint = Environment.GetEnvironmentVariable("MQTTBroker");
var clientConfig = new AmazonIotDataConfig { ServiceURL = mqttBrokerEndpoint };
return new AmazonIotDataClient(clientConfig);
And the ServiceURL is https://.iot.us-east-1.amazonaws.com
How do I test that this broker is good. Are there any other tools I should be using to try and identify why I am getting SSL errors?

While hitting from Postman i am able to access data without authrization but why not with angular 2 application

I am using a ASP.Net Web API. When i am selecting no authentication while creating web API project the same code works but when i use individual authentication it throws 401 error even after trying all possible tricks. Please help me to handle different authentication modes available in ASP. Net project creation. I did not find any proper document on individual authentication even on MSDN.
Also suggest me the recommended way to send token or credentials to the web API.
The below written code is of Angular 2 service. getOneItemDetailsCallClient is working but getOneItemDetailsCall throws 401
getOneItemDetailsCall():Observable<any>{
return this.http.get('http://localhost:56265/api/ProductDetail').map((response:Response)=>response.json());
}
getOneItemDetailsCallClient():Observable<any[]>{
return this.http.get('https://my-json-server.typicode.com/typicode/demo/posts').map((response:Response)=><OneItemComponent[]>response.json());
}
Error details:
Request URL: http://localhost:56265/api/ProductDetail
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: [::1]:56265
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: GET,POST,PUT,DELETE,OPTIONS
Access-Control-Allow-Methods: true
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 6161
Content-Type: text/html; charset=utf-8
Date: Thu, 06 Sep 2018 18:04:04 GMT
Server: Microsoft-IIS/10.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcdmlwdWxzaW5naFxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDE1XFByb2plY3RzXEZsaXBab25fQmFja2VuZFxGbGlwWm9uX0JhY2tlbmRcYXBpXFByb2R1Y3REZXRhaWw=?=
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:56265
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/OneItem
You are accessing the api from a different domain than the API is hosted so it is blocking your requests. Adding cross origin requests (CORS) should resolve your problem. Here is a link to ASP.NET Core CORS docs.
In Startup.cs You should be able to call:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
But may need to specify your Angular host app as the origin:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder =>
builder.WithOrigins("http://localhost:4200"));
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}

POST GWT CORS request works but PUT CORS request doesn't

I'm writing a GWT frontend for a personal project, and I'm having problems with some HTTP requests. When I do a CORS POST request, it works fine
String url = BASE_URL + "students/";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);
try {
builder.sendRequest(studentWriter.write(student), new RequestCallback() {
public void onError(Request request, Throwable exception) {
addItemDialog.close();
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("No response");
responseLabel.setText(request.toString());
}
public void onResponseReceived(Request request, Response response) {
loadingIcon.setVisible(false);
String responseText = response.getText();
List<Map.Entry<Integer, Student>> students = model.getList();
Integer studentId = Integer.parseInt(responseText);
students.add(new AbstractMap.SimpleEntry<>(studentId, student));
model.setList(students);
// clear text fields
className.setValue("");
additionLevel.setValue("");
additionProblems.setValue("");
subtractionLevel.setValue("");
subtractionProblems.setValue("");
multiplicationLevel.setValue("");
multiplicationProblems.setValue("");
divisionLevel.setValue("");
divisionProblems.setValue("");
addItemDialog.close();
}
});
} catch (RequestException _) {
// Code omitted for clarity
}
The options request gets a 200 response (chrome network inspection below):
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:OPTIONS
Status Code:200
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:post, get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:56:32 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:8nJ2gzqHFPiiDOOeEelzkpI7Ga9SFdEcljiLt2pvm7Z995_GicxPVw==
x-amzn-requestid:bb0e23db-9893-11e7-bbbe-9bea7d9d70bf
x-amzn-trace-id:sampled=0;root=1-59b94720-d892209d8c5c2a04832bdb85
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:POST
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
and then the POST request occurs as expected
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:POST
Status Code:201
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-origin:*
content-length:1
content-type:application/json
date:Wed, 13 Sep 2017 14:56:33 GMT
status:201
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:gxYrwctM75ObiPyS4nD69jXSO4dBaMAOZmXXX0mPE4wMgCdcjUSQsA==
x-amzn-requestid:bb381a33-9893-11e7-a1f1-17fd67ca388c
x-amzn-trace-id:sampled=0;root=1-59b94720-1c1e3a8d8c9ce2741c789241
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:POST
:path:/v1/students/
:scheme:https
accept:application/json
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
content-length:224
content-type:application/vnd.onelostlogician.student+json
lambda-authorization:Basic [redacted]
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Request Payload
{"className":"6T","additionProblemId":4,"additionNoOfProblems":5,"subtractionProblemId":3,"subtractionNoOfProblems":5,"multiplicationProblemId":2,"multiplicationNoOfProblems":5,"divisionProblemId":1,"divisionNoOfProblems":5}
Unfortunately, a PUT request to a very similar resource, on the same server, doesn't. The code is almost identical:
String url = BASE_URL + "students/" + studentId;
RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);
try {
builder.sendRequest(studentWriter.write(student), new RequestCallback() {
public void onError(Request request, Throwable exception) {
addItemDialog.close();
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("No response");
responseLabel.setText(request.toString());
}
public void onResponseReceived(Request request, Response response) {
loadingIcon.setVisible(false);
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("Response: " + response.getStatusCode());
responseLabel.setText(response.getText());
}
});
} catch (RequestException _) {
// Code omitted for clarity
}
The options request gets a 200 response:
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/4
Request Method:OPTIONS
Status Code:200
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:58:38 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:0PoyOa6oDBSmU7iCWZyeSZFqWxZvumN8C4GtHn8rsoJK5AURbj3kxQ==
x-amzn-requestid:063270d4-9894-11e7-9d66-71b07b2689ef
x-amzn-trace-id:sampled=0;root=1-59b9479e-39be94b25784b92027fa2753
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/4
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:PUT
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
…but after receiving a successful OPTIONS response, it does not make the PUT request at all.
In the Chrome console I get:
XMLHTTPRequest cannot load https://[redacted]/v1/students/5. Method
PUT is not allowed by Access-Control-Allow-Methods in preflight
response
I don't understand that error, given that we can see "put" in the access-control-allow-methods response header for the preflight OPTIONS request shown above.
Any ideas what I'm doing wrong?
In the POST response, the allowed methods header is
access-control-allow-methods:post, get, put
In the PUT response, the allowed methods header is
access-control-allow-methods:get, put
Note that the required method is the first in the list of the POST case, but second in the list in the PUT case. When I modified the server to put the method under consideration first in the list (and, also, to make it case sensitive, because HTTP method names are case sensitive), the browser then performed the required followup PUT request.

Signalr 404 error after moving to iis7 server

I have a signalr service that is working fine on my development environment when hosted in IIS 8.
When the service is moved to our QA server using IIS 7.5, attempting to connect to my hub results in this error:
System.AggregateException: One or more errors occurred. ---> Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: private
Date: Thu, 06 Mar 2014 20:09:35 GMT
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Content-Length: 5307
Content-Type: text/html; charset=utf-8
}
at Microsoft.AspNet.SignalR.Client.Http.DefaultHttpClient.<>c__DisplayClass2.<Get>b__1(HttpResponseMessage responseMessage)
at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass19`2.<Then>b__17(Task`1 t)
at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass3a.<RunTask>b__39(Task`1 t)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at ConsoleApplication2.Program.Main(String[] args)
---> (Inner Exception #0) Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: private
Date: Thu, 06 Mar 2014 20:09:35 GMT
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Content-Length: 5307
Content-Type: text/html; charset=utf-8
}
at Microsoft.AspNet.SignalR.Client.Http.DefaultHttpClient.<>c__DisplayClass2.<Get>b__1(HttpResponseMessage responseMessage)
at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass19`2.<Then>b__17(Task`1 t)
at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass3a.<RunTask>b__39(Task`1 t)<---
My Startup class
[assembly: OwinStartup(typeof(SignalRStartup))]
public class SignalRStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR("/restricted/signalr", new HubConfiguration());
}
}
And attempting to start a connection in the c# client
HubConnection foo = new HubConnection("http://localhost/ccwebdev/restricted");
foo.Start().Wait();
The QA server is running windows server 2008 r2 SP1, so it should have support for extensionless urls.
I also tried adding this to my web.config
<modules runAllManagedModulesForAllRequests="true"/>
The app pools are in integrated mode, not classic mode
I have read many other similar SO posts and the troubleshooting guide for 404's here: http://www.asp.net/signalr/overview/signalr-20/troubleshooting-and-debugging/troubleshooting#other,
but with no luck.
Can anyone provide any other troubleshooting steps I can try?
EDIT
changing my map call to app.MapSignalR("/restricted", new HubConfiguration());
causes an exception to be thrown on service startup
[InvalidOperationException: Protocol error: Unknown transport.]
Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(HostContext context) +384
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ProcessRequest(HostContext context) +502
Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary`2 environment) +328
Microsoft.Owin.Mapping.<Invoke>d__0.MoveNext() +611
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +208
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +434
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Did you try to manually patch the server for extensionless URLs? I'm not sure if server 2008 R2 SP1 includes that patch- you can give it a try and see:
http://support.microsoft.com/kb/980368

Resources