Sql Injection in Aspnet with Bearer Tokens
Sql Injection in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
SQL injection in ASP.NET occurs when user-controlled input is concatenated into SQL queries without proper parameterization or validation. The presence of bearer tokens does not prevent SQL injection; if a token is extracted from an Authorization header and then used unsafely in a query (for example to look up user roles or tenant information), it becomes an additional input vector. Because bearer tokens are often long, opaque strings, developers might mistakenly treat them as safe and concatenate them directly into SQL text, bypassing parameterized expectations.
Consider a scenario where an endpoint extracts the bearer token and uses it to fetch user permissions: building SQL by string interpolation with token values introduces the same risks as any other string input. Attackers can supply crafted tokens containing SQL metacharacters to manipulate query logic, bypass authentication, or extract data. This becomes particularly relevant when token handling intersects with dynamic queries, reporting routines, or multi-tenant lookups where the token influences the WHERE clause. Even if the token comes from a trusted authentication layer, it must be treated as untrusted input.
Common vulnerable patterns include string-based query construction with string.Format or interpolation, dynamic LINQ that still ends up as concatenated SQL, and misuse of ExecuteSqlRaw without parameter placeholders. For example, concatenating a token into a raw query exposes the application to classic injection techniques such as UNION-based data exfiltration or authentication bypass. The OWASP API Top 10 and related frameworks classify these as injection flaws, and they remain relevant whether or not bearer tokens are present. In ASP.NET, parameterized queries, stored procedures with parameters, and strict input validation mitigate these risks; treating bearer tokens as implicit trust undermines those controls.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
To remediate SQL injection risks when working with bearer tokens in ASP.NET, always use parameterized queries and avoid any form of string concatenation or interpolation that incorporates token values. Treat the token as an opaque identifier and pass it to the database via parameters, not via text composition. Below are concrete, safe patterns for ASP.NET with C#.
Safe parameterized query with SqlCommand
using System.Data.SqlClient;
public async Task GetUserDataAsync(string bearerToken)
{
await using var connection = new SqlConnection(Configuration.GetConnectionString("Default"));
await connection.OpenAsync();
// Correct: parameterize the token input
var command = new SqlCommand("SELECT Username, Role FROM Users WHERE AccessToken = @token", connection);
command.Parameters.Add(new SqlParameter("@token", System.Data.SqlDbType.NVarChar, 500) { Value = bearerToken });
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var username = reader.GetString(0);
var role = reader.GetString(1);
// process user data
}
}
Safe usage with Dapper (parameter object)
using Dapper;
public async Task LookupByTokenAsync(string bearerToken)
{
await using var connection = new SqlConnection(Configuration.GetConnectionString("Default"));
await connection.OpenAsync();
var sql = "SELECT Id, Username, Scope FROM Tokens WHERE BearerToken = @BearerToken";
var result = await connection.QueryFirstOrDefaultAsync(sql, new { BearerToken = bearerToken });
return result;
}
Entity Framework Core with parameterized raw SQL
using Microsoft.EntityFrameworkCore;
public async Task FindByTokenRawAsync(string bearerToken)
{
await using var context = new AppDbContext();
// Use FromSqlRaw with parameters; do not interpolate token into the SQL string
var user = await context.Users
.FromSqlRaw("SELECT * FROM Users WHERE AccessToken = {0}", bearerToken)
.FirstOrDefaultAsync();
return user;
}
Validation and length constraints
In addition to parameterization, apply strict validation for bearer tokens before using them in any data access path. For example, enforce expected format (e.g., base64url characters), length limits, and reject tokens containing suspicious characters. This complements but does not replace parameterization.
if (string.IsNullOrWhiteSpace(bearerToken) || bearerToken.Length > 1000 || !Regex.IsMatch(bearerToken, "^[A-Za-z0-9\-_]+\.?[A-Za-z0-9\-_]+\.?[A-Za-z0-9\-_]+$"))
{
throw new SecurityException("Invalid token format.");
}Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |