The i2b Global Blog stands as a lighthouse in the ever-changing digital seascape. Rooted in decades of web technology and IT expertise, we bring you a curated blend of advice, news, and insights from the frontlines of web development, SEO, and digital security. As the digital world evolves, our mission remains clear: to equip you with the knowledge needed to thrive. Dive into our posts, and let's shape the digital future side by side.

Prioritize safety: Essential guides to safeguarding your digital presence.

Securing Your ASP.NET Core REST API: Best Practices for Safety & Performance

 Monday, November 18, 2024     Bojan Arsenovic     Secure Websites

Featured Photo

In today's digital landscape, securing APIs is critical for businesses and developers alike. APIs are the backbone of modern applications, enabling data exchange and powering services across platforms. Without proper security measures, APIs become a target for malicious actors, leading to data breaches, service disruptions, and reputational damage.

Why API Security Matters

APIs expose your services to external and internal consumers, making them a prime target for bots, unauthorized users, and hackers. Common risks include:

  • Bots and Automated Attacks: Malicious actors use bots to flood your API with requests, often targeting non-existent endpoints or testing for vulnerabilities.
  • Unauthorized Access: Without proper access controls, sensitive endpoints are exposed to unauthorized users.
  • Performance Impacts: Unregulated API requests can overload servers, leading to degraded performance.
  • Data Breaches: An insecure API can expose private data, risking your reputation and compliance with regulations.

How to Secure Your API

Here's how to implement effective security for your ASP.NET Core REST APIs:

1. Implement Security Headers

Security headers help protect your API against a range of attacks, including cross-site scripting (XSS) and clickjacking. Use middleware to add these headers:


context.Response.Headers.XContentTypeOptions = "nosniff";
context.Response.Headers.XFrameOptions = "DENY";
context.Response.Headers["Permissions-Policy"] = "none";
    

These headers ensure your API's content cannot be misused or embedded maliciously.

2. Enforce HTTPS and HSTS

Secure your API by enforcing HTTPS for all communications. HTTPS encrypts data in transit, protecting it from interception. Add HSTS (HTTP Strict Transport Security) to ensure browsers only communicate over secure channels:


if (app.Environment.IsProduction())
{
    app.UseHsts();
}
app.UseHttpsRedirection();
    

3. Restrict Unnecessary HTTP Methods

Disable unused HTTP methods to reduce your API's attack surface. For example, if your API only uses `POST` and `OPTIONS`, deny other methods with middleware:


if (!_allowedMethods.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
{
    context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
    context.Response.Headers.Allow = string.Join(", ", _allowedMethods);
    await context.Response.WriteAsync("Method Not Allowed");
    return;
}
    

4. Use API Keys for Access Control

Restrict access to your API by validating API keys for incoming requests. This ensures only authorized clients can access your resources. Implement an API key middleware to verify keys against a whitelist:


public async Task InvokeAsync(HttpContext context)
{
    if (!context.Request.Headers.TryGetValue("X-Api-Key", out var apiKey) || !IsValidApiKey(apiKey))
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        await context.Response.WriteAsync("Unauthorized");
        return;
    }
    await _next(context);
}
    

5. Use JWT Tokens for Authentication

For more secure and scalable access control, use JSON Web Tokens (JWT). JWTs are self-contained tokens signed with a secret key or certificate, containing claims that represent user permissions:


services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your-issuer",
            ValidAudience = "your-audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
        };
    });
    

6. Configure CORS for Secure Cross-Origin Requests

Cross-Origin Resource Sharing (CORS) policies determine which domains can access your API. Only allow trusted origins to prevent unauthorized access:


builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", builder =>
    {
        builder.WithOrigins("https://trusted-origin.com")
               .AllowAnyHeader()
               .AllowAnyMethod();
    });
});
app.UseCors("AllowSpecificOrigins");
    

7. Use Rate Limiters

Protect your API from abuse by implementing rate limiting based on IP addresses. Microsoft now provides built-in packages for rate limiting. For more granular control, you can also use Polly:


builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("Fixed", limiter =>
    {
        limiter.Window = TimeSpan.FromMinutes(1);
        limiter.PermitLimit = 100; // Limit to 100 requests per minute
        limiter.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        limiter.QueueLimit = 2; // Allow 2 queued requests
    });
});
app.UseRateLimiter();
    

8. Centralize Security in Middleware

Use middleware to centralize your API's security logic, such as adding security headers, enforcing HTTP method restrictions, and rate limiting:


public class SecurityHeadersMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string[] _allowedMethods;

    public SecurityHeadersMiddleware(RequestDelegate next, string[] allowedMethods)
    {
        _next = next ?? throw new ArgumentNullException(nameof(next));
        _allowedMethods = allowedMethods ?? new[] { "POST", "OPTIONS" };
    }

    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers.XContentTypeOptions = "nosniff";
        context.Response.Headers.XFrameOptions = "DENY";
        context.Response.Headers["Permissions-Policy"] = "none";

        if (!_allowedMethods.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
        {
            context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
            context.Response.Headers.Allow = string.Join(", ", _allowedMethods);
            await context.Response.WriteAsync("Method Not Allowed");
            return;
        }

        await _next(context);
    }
}
    

Who Should Secure Their API?

Securing APIs is not just for large enterprises; it’s essential for any organization exposing application data or services via APIs. Some key scenarios include:

  • Public APIs: APIs accessed by mobile apps, SPAs (Single Page Applications), or external developers need robust security to prevent unauthorized access or abuse.
  • Internal APIs: Even internal APIs require security to safeguard sensitive business data and maintain operational integrity.
  • Data-Centric APIs: APIs processing private user data, such as payment information or personal identifiable information (PII), must comply with legal regulations like GDPR or HIPAA.
  • High-Traffic APIs: APIs with significant traffic, such as e-commerce or streaming platforms, need rate limiters to prevent abuse and ensure stability.

Regardless of your industry or business size, securing your APIs protects your customers, your data, and your brand reputation.

When to Secure Your API?

Security should be part of your API development lifecycle from the beginning. Waiting until after deployment often results in patchwork fixes that can leave gaps. Here’s when to focus on API security:

  • During Design: Plan your security measures during the API design phase. Identify sensitive endpoints and decide on access controls and encryption requirements.
  • During Development: Implement security headers, rate limiting, and HTTPS enforcement as part of your coding process. Regularly test for vulnerabilities using automated tools.
  • During Deployment: Ensure proper configuration of environment-specific settings, such as enabling HSTS and disabling unnecessary methods in production.
  • Post-Deployment: Continuously monitor for threats and apply updates to keep your API secure as new vulnerabilities emerge.

By integrating security throughout the lifecycle, you ensure your API is protected at every stage.

Are you ready to secure and optimize your API with ASP.NET Core? Our team specializes in ASP.NET Core development and can help you implement robust security measures, including HTTPS enforcement, rate limiting, and middleware-driven security headers. Contact i2b Global today to discuss your API project and discover how we can help you protect your data, enhance performance, and achieve your business goals.


Chrome will show all HTTP sites as "not secure" starting in July 2018

 Wednesday, June 13, 2018     Bob Gill     Search Engine Optimization Secure Websites

Featured Photo

A few years ago Google began advising webmasters that they were going to start favouring websites that were secured with an SSL Certificate in their search results. They hinted that they were going to give more consideration to sites that were secure versus those that were not in their search results. (Similar to their position on mobile friendliness and speed of websites). About a year ago Google started warning webmasters and site owners that the Google Chrome Browser was going start showing warnings to visitors of sites and web pages that were not secure and contained login forms, or forms collecting personal information.

Recently Google has cranked up the pressure on website owners to make their websites secure.

Starting in July of 2018, Google Chrome will mark all non-secure (HTTP) sites as “not secure,” according to a blog post published today by Chrome security product manager Emily Schechter. Chrome currently displays a neutral information icon, but starting with version 68, the browser will warn users with an extra notification in the address bar. Chrome currently marks HTTPS-encrypted sites with a green lock icon and “Secure” sign.

Google has been nudging users away from unencrypted sites for years, but this is the most forceful nudge yet. Google search began down-ranking unencrypted sites in 2015, and the following year, the Chrome team instituted a similar warning for unencrypted password fields.

And it’s not just the Google’s Chrome browser that is presenting these warnings currently. Microsoft’s IE Edge and Firefox are also displaying the neutral info icon in the address bar to warn visitors about the non-secure website.

Google is trying to persuade all site owners to operate their websites over the secure protocol. The Chrome team said today’s announcement was mostly brought on by increased HTTPS adoption. Eighty-one of the top 100 sites on the web are secure (HTTPS), and a strong majority of Chrome traffic is already encrypted. “Based on the awesome rate that sites have been migrating to HTTPS and the strong trajectory through this year,” Schechter said, “we think that in July the balance will be tipped enough so that we can mark all HTTP sites.”

The added bonus is that securing your website is also good for Search Engine Optimization. Contact us for more information or if you would like our assistance to help secure your website.
Give us a call or complete our contact form Note: There is a fee to purchase an SSL Certificate and install it on your website.

For more websmaster tips be sure to check out our SEO Trends in 2018 Blog Article



Google Rating

4.6      10 reviews


Photo of Sam Barb

Sam Barb
  February 08, 2025

Bob at i2b global has been fantastic to deal with. I've been using this firm since 1995 and they have never let me down. I believe they are to notch and always perform beyond our expectations. I would highly recommend Bob and his team to all my family and friends. GREAT WORK!!!

Photo of D R

D R
  July 20, 2023

We have been using I2B Global for over 5 years and for multiple business ventures, and we could not be more pleased with the service we have received. Bob and his team have been incredibly accommodating, supportive, and always share their wealth of experience. I could not recommend I2B Global more, Thanks for all your work.

Photo of Ramon P. Schuler

Ramon P. Schuler
  February 19, 2022

AMAZING COMPANY WITH FOLKS WHO CARE!! RPS

Photo of Ace Luxury

Ace Luxury
  August 22, 2021

To Bob, Bojan, and the I2B Global Team: Thank you so much for the outstanding work you have done for us so far. Your way of responding to our needs is truly a breath of fresh air in this fast paced era we live in. We continue to add more services your firm has to offer given how effective your site design and SEO has been. We look forward to continued growth along with you for years to come. Keep up the excellent work.

Photo of Grant McGuinty

Grant McGuinty
  March 19, 2021

As a neophyte in the software business I cannot express enough how happy I am to deal with Bob Gill at i2b Global Inc. The company is with me every step of the way. Kind, professional and very responsive are the best words to describe them. I look forward to grow with them in the future with my FinalDocx by Executor Choice distribution business.

View All Google Reviews


 Request a Quote