We have a requirement of disabling the HTTP methods besides POST, GET and Head in an ASPNET Core Web application due as a part of security fixes. How can we disable the HTTP OPTIONS method in ASP.Net core API?
Allowed 3 methods which are POST,GET and Head.
How to block all the others method which I didn't use in middleware like DELETE,TRACE,PATCH and etc.
Needs to return Error Code 405 = Method Not Allowed . Currently it throws the error 500 which is Internal Server Error
my code right now .
app.Use(async (context, next) =>
{
if (context.Request.Method=="TRACE")
{
context.Response.StatusCode = 405;
return;
}
await next.Invoke();
});
How to Block Http Methods in ASP.NET
You could try as below:
app.MapWhen(x => x.Request.Method == "somemethod",
y => y.Use(async(context,next)=>
{
context.Response.StatusCode = 405;
await context.Response.WriteAsync("Method Not Allowed");
}
));
The Result:
Related
We have containerized our DotNetCore app using Docker and running on OpenShift.
We are add few custom response headers and we observed that the custom response headers are returned in Lower case though we specify like "Header-Name" it returns as "header-name"
Googling showed that this is a specification with Http2 protocol.
We tried writing custom middleware to remove the header and add a header again. but still the response headers are in lower case
app.Use(
next =>
{
return async context =>
{
var stopWatch = new Stopwatch();
stopWatch.Start();
context.Response.OnStarting(
() =>
{
stopWatch.Stop();
context.Response.Headers.Add("X-ResponseTime-Ms", stopWatch.ElapsedMilliseconds.ToString());
//returns in lower case
return Task.CompletedTask;
});
await next(context);
};
});
How could we solve this, any hack to solve this ?
I'm using IdentityServer 4 as oauth for my application ( Reactjs ) I'm running Identityserver on port http://localhost:5000 and reactjs app on http://localhost:3000. I have tried using CORS for my idenityserver4 with the following code.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer(options =>
{
options.Events.RaiseSuccessEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseErrorEvents = true;
})
.AddClientStore<ClientStore>()
//.AddInMemoryApiResources(Config.GetApiResources())
.AddResourceStore<ResourceStore>()
//.AddInMemoryClients(Config.GetClients())
.AddCustomUserStore()
.AddCertificateFromFile();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins( "http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
{
app.UseForwardedHeaders();
if (environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
//app.UseCors("default");
app.UseIdentityServer();
app.UseStaticFiles();
// uncomment, if you want to add an MVC-based UI
app.UseMvcWithDefaultRoute();
}
}
Even though I have added localhost:3000 in WithOrigins(), when I try to make a request from react app with axios I'm getting the following blocked error.
Can someone help me to know where I'm doing wrong. I need my application to only allow some list of origins (apps)
Thanks
It's likely this could be because of the trailing slash, this is mentioned in the documentation.
Note: The specified URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.
Try http://localhost:3000 instead of http://localhost:3000/.
I'd also question the usage of both .AllowAnyOrigin() and .WithOrigins(). What you're looking to achieve should be possible using only .WithOrigins().
If you are sending a request to another domain, try sending a http request from your identity server not react.js app. I encountered a similar issue but i just used my API as a proxy and it worked fine.
I am trying to use a get request on my web page (made in angular) that refers to my own api (created with APS.NET core). I get the following error in my chrome debugging tool:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
This is odd, because i put the following in my startup.cs:
app.UseCors(builder =>
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
So everything should be allowed?
This is the code i use for the GET request:
ngOnInit(){
debugger;
this._svc.getAllMagicItems().subscribe(result =>{
debugger;
console.log(result);
debugger;
this.items = Array.of(result);
debugger;
})
}
getAllMagicItems() executes this code:
getAllMagicItems(): Observable<IImageRootObject> {
return this._http.get<IImageRootObject>("http://localhost:63514/api/v1/MagicItem");
}
How do I solve this CORSE problem?
Like this post Giancarlo Benitez provided shows, my problem lied in calling services.AddCors() and services.AddMVC(). My problem was that I called AddMVC() first, but the CORS-headers need to be allowed before MVC initializes. So load them in this order:
public void ConfigureServices(IServiceCollection services) {
services.AddCors(); /* <----- Added this line before de MVC */
services.AddMvc();
}
after merging angular app with asp.net MVC calling API from angular returns an empty JSON.
The angular and asp.net are in the same domain.
If I call the API With PostMan, I have a JSON with the result. but if I call it in the angular app my JSON result is empty.
Are there any tips for communicating angular app with asp.net MVC after merging and serving in the same domain?
Update 1:
The code that used to calling Webservice:
getSheets(): Observable<Sheet[]> {
return this.http.get(this.config.apiUrl + '/api/SheetsRelationAPI',
this.jwt())
.map(this.extractData)
.do(data => console.log('SheetsData:', data)) // debug
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
// private helper methods
private jwt() {
// create authorization header with jwt token
const currentUser = JSON.parse(atob(this.cookie.getCookie('currentUser')));
if (currentUser && currentUser.access_token) {
const headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.access_token},
);
return new RequestOptions({ headers: headers });
}
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
Update 2:
I notice that my API if I called it from outside domain it respond 2 times:
inspecting network with google chrome inspect element:
the first response is "zone.js" initiator and the second response is an "other" initiator
If I call the API from inside of the Domain I just have a response from "zone.js" initiator and it returns an empty JSON.
Update 3
export class OtherComponent implements OnInit {
sheets: Sheet[] = [];
errorMessage: string;
constructor(private httpService: HttpService) {
// this.sheets = this.ichartHttp.getSheets();
// console.log(this.sheets);
}
getSheets() {
this.httpService.getSheets()
.subscribe(
sheets => this.sheets = sheets,
error => this.errorMessage = <any>error
);
}
ngOnInit() {
this.getSheets();
}
}
The Problem is with my Authentication methods,
I use two types of authentication, MVC and WebAPI they conflict if I send a request to API under the same Domain.
So my Answer is: Your Angular Code looks good, take a look at your middleware project
I am new in Angular 2, in my Angular 2 project I create API call service that return json data.
this._http.post(this.url, body, options)
.map(response => response.json())
.catch(this.handleError);
Let say this service return 401 Http Response unauthorized and I tried get the status error, so I can redirect to Login Page and show error message
.subscribe(
login => this.login=login,
error => this.errorMessage = <any>error);
}
but why response code did not throw as error, and only show result
Failed to load resource: the server responded with a status of 401 (Unauthorized) and end the task ?
when I debug the code, the result generated in this line code
this.invoke = function () {
try {
return zone.runTask(self, this, arguments);
}
finally {
drainMicroTaskQueue();
}
};
}
any suggestion ?
Thank You