C
C#17mo ago
Lakhey_Wala

❔ Need help implementing CORS and IP-based access control in ASP.NET Core Web API

I'm currently working on an ASP.NET Core Web API project and I need assistance with implementing CORS (Cross-Origin Resource Sharing) and IP-based access control. Here's the scenario: I have a requirement to allow access to the API only from devices whose IP addresses are registered in a database. If the IP address of the device making the request doesn't match any of the registered IP addresses, the content should not be accessible. To achieve this, I'm planning to use custom middleware. I would greatly appreciate any guidance or code examples on how to accomplish this in ASP.NET Core. Specifically, I'm looking for help with: Setting up CORS to allow cross-origin requests. Retrieving the IP address of the device making the request. Validating the IP address against the database records. Blocking access if the IP address is not found in the database. Any insights, best practices, or code snippets you can provide would be highly appreciated. Thank you in advance for your help!
9 Replies
Shinigami
Shinigami17mo ago
Stack Overflow
How to get a user's client IP address in ASP.NET?
We have Request.UserHostAddress to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can ...
Shinigami
Shinigami17mo ago
I found something for you, can check the ip from http request headers but i haven't implemented it so you might want to check it out
Lakhey_Wala
Lakhey_WalaOP17mo ago
Thank you for offering me help. I will check it out and let you know if it makes any progress.
Shinigami
Shinigami17mo ago
Sure please let me know
Lakhey_Wala
Lakhey_WalaOP17mo ago
ok 😊 I was searchin for CORS related problem but the link you provided don't talk about CORS only of ipAddress. 😅
Florian Voß
Florian Voß17mo ago
Setting up CORS to allow cross-origin requests.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0 this will give you an overview about CORS in asp.net core. Here a sample that allows Everything:
builder.Services.AddCors(options => options.AddPolicy("AllowAll", policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()))
builder.Services.AddCors(options => options.AddPolicy("AllowAll", policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()))
Enable Cross-Origin Requests (CORS) in ASP.NET Core
Learn how CORS as a standard for allowing or rejecting cross-origin requests in an ASP.NET Core app.
Lakhey_Wala
Lakhey_WalaOP17mo ago
Thank you @voflorian99
Florian Voß
Florian Voß17mo ago
if your issue has been solved, don't forget to /close the thread
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server