LESSON 15 OF 15

Security Vulnerabilities, Testing and Production Readiness

Review common authentication and authorization weaknesses, test security controls, and prepare an ASP.NET Core production checklist.

70 dk 89

Introduction

In this final lesson, we will review the ASP.NET Core Identity, Cookie Authentication, JWT, refresh token and authorization infrastructure from an attacker’s perspective. The goal is not to add another authentication feature, but to determine whether the existing design resists misconfiguration, information disclosure and privilege escalation.

Our work has three stages: identify threats, perform automated and manual tests, and create a production-readiness checklist. Security must be addressed throughout development, testing, deployment, monitoring and maintenance—not only when a request reaches the application.

1. Threat modeling and review scope

Begin by identifying the assets you are protecting and the possible attackers. Passwords, Identity tables, access tokens, refresh token records, email-confirmation links and administrative operations are high-value assets. An attacker may be an anonymous internet user, a user with a compromised account, a malicious client or a low-privileged user inside the application.

Ask the following questions for every endpoint:

  • Does the endpoint require authentication?
  • Can every authenticated user access the resource?
  • Is resource ownership checked?
  • Is the request protected by a cookie or a bearer token?
  • If the request comes from a browser, is it exposed to CSRF?
  • Does the error response reveal unnecessary information about users, tokens or the system?

This is safer than checking only whether [Authorize] was added. For example, [Authorize] blocks anonymous access, but it does not by itself prove that a user cannot read another user’s record by changing an id value.

2. Reviewing token and cookie leakage

Access and refresh token security

Access tokens should have a short lifetime and contain only the claims that are necessary. Do not place passwords, signing secrets, sensitive profile information or rapidly changing permissions in a token. A signed JWT is not encrypted; a party that can read the token can normally read its payload.

For refresh tokens, storing a secure hash instead of the raw value in the database is a stronger design. During renewal, hash the supplied value with the same algorithm and compare it with the stored record. A refresh token can be designed for one-time use or rotation:

  1. The client sends the refresh token.
  2. The server checks its lifetime, revocation state and relationship to the user.
  3. The valid token is revoked.
  4. A new access token and refresh token are issued.
  5. If an old refresh token is reused, revoke the related token family and record a security event.

Never transport tokens in a URL query string. URLs can appear in browser history, proxy logs, analytics systems or the Referer header. Use HTTPS, never log access or refresh token values, and do not include them in exception messages.

Cookie checks

For cookie-based sessions, production deployments should use appropriate Secure, HttpOnly and SameSite settings. HttpOnly prevents JavaScript from directly reading a cookie; it does not remove the risk of XSS. Secure restricts transmission to HTTPS. The correct SameSite value depends on whether the application must support same-site or cross-site scenarios.

Do not publish an authentication cookie with an unnecessarily broad Domain or Path. Define the session lifetime, sliding-expiration behavior and whether sensitive operations require re-authentication. When a user signs out, revoke refresh token records and, where appropriate, other active sessions on the server.

Storing JWTs or refresh tokens in localStorage is risky for browser applications because JavaScript can read them if an XSS vulnerability is present. Prefer an HttpOnly cookie or a Backend-for-Frontend design for browser-based clients. If another storage mechanism is required by the client architecture, document the accepted risk and apply strong XSS defenses.

3. Testing CSRF and CORS

CSRF

Because browsers automatically send cookies, state-changing requests protected by cookies can be exposed to CSRF. Password changes, email updates, role assignments and payment operations must not be implemented as GET requests. Use POST, PUT, PATCH or DELETE, and enable antiforgery validation where appropriate.

For Razor or MVC forms, test that an antiforgery token is generated and validated. Confirm that a request without a token, or with an invalid token, is rejected. An API that explicitly receives a bearer token in the Authorization header is different from a cookie-based CSRF scenario; however, this does not eliminate XSS or token-leakage risks.

CORS

CORS is not an authentication mechanism. It controls when a browser may send cross-origin requests or expose responses to client-side JavaScript. In production, do not combine AllowAnyOrigin with AllowCredentials. List trusted origins explicitly:

builder.Services.AddCors(options => options.AddPolicy("Frontend", policy =>    policy.WithOrigins("https://app.example.test")          .AllowAnyHeader()          .AllowAnyMethod()          .AllowCredentials()));

The actual production domain should come from controlled configuration rather than an example value. Test that expected preflight OPTIONS requests succeed and that an untrusted origin cannot obtain a browser-readable response. CORS does not stop a malicious non-browser client from calling the server directly, so the API still needs authentication and authorization.

4. Enumeration, password policy and error responses

Review login, registration, password-reset and email-confirmation flows for user-enumeration weaknesses. Messages such as “this email is not registered” or “the account exists but the password is wrong” reveal whether an account exists. Show a generic message to the user and keep technical details in protected logs.

Compare the response body, HTTP status code and approximate response time. Returning immediately when a user does not exist while calculating a password hash for an existing user can create a timing difference. For sensitive flows, use comparable processing steps and an appropriate rate-limiting policy.

Reject short and predictable passwords, allow long passphrases, and consider blocking common or previously breached passwords. Do not implement your own password storage with SHA-256. Use ASP.NET Core Identity’s password hasher and validation pipeline. Never store passwords in plaintext, reversible encryption or log files.

Account lockout requires a balance between security and usability. An overly aggressive policy can allow attackers to lock other users’ accounts deliberately. Monitor failed logins, lockouts, password-reset requests and suspicious refresh-token reuse.

5. Testing authorization flaws

Authorization tests should include at least four cases for every protected endpoint: anonymous user, normal authenticated user, owner of a different resource and administrator. Verify that user A cannot read or update user B’s resource merely by changing an id. Hiding a button in the client interface is not security; the server must enforce the rule.

Instead of scattering role and policy names as string literals, use centralized constants or policy registration. Verify that roles and claims in a token were issued by the trusted issuer. Decide how to reduce the effect of long-lived tokens after a user’s role changes. Short token lifetimes, security-stamp validation or a server-side revocation mechanism may be appropriate depending on the architecture.

6. Automated integration tests

Security controls should not depend only on manual review. Use WebApplicationFactory<Program> to create a test server and verify expected endpoint status codes. Do not use production secrets in tests; isolate the database and provide a controlled identity through a test authentication handler.

[Fact]public async Task NormalUser_CannotReadAnotherUsersOrder(){    var client = _factory.CreateClient();    client.DefaultRequestHeaders.Authorization =        new AuthenticationHeaderValue("TestScheme");    var response = await client.GetAsync("/api/orders/other-user-order");    Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);}

Write similar tests for an anonymous request returning 401 Unauthorized, an authenticated but unauthorized user receiving 403 Forbidden, an invalid JWT being rejected, a cookie request without an antiforgery token being denied and an untrusted CORS origin being refused by the browser. Disabling automatic redirects in tests makes the actual HTTP status easier to verify.

7. Production-readiness checklist

AreaCheck
HTTPSAre all credentials and token exchanges protected by HTTPS?
SecretsAre JWT keys, connection strings and email secrets outside the source code?
CookiesAre Secure, HttpOnly, SameSite and expiration configured appropriately?
TokensAre issuer, audience, signature, lifetime and clock skew validated?
CSRF/CORSAre cookie-based writes protected and trusted origins narrowly defined?
AuthorizationHave ownership and sensitive-operation checks been tested server-side?
LoggingAre security events monitored without logging tokens, passwords or unnecessary personal data?
OperationsAre alerting, backups, key rotation and incident-response procedures documented?

8. Short practice exercise

  1. Compare failed login requests for an existing and a nonexistent user by status code, response body and approximate duration.
  2. Write three authorization tests for an administrator, a resource owner and a different user.
  3. Verify that the raw refresh token does not appear in logs or database records.
  4. Send a cookie-authenticated update request without an antiforgery token and observe the expected rejection.
  5. Create a production security checklist containing at least ten items for your team.

Conclusion

A secure authentication infrastructure is not a single middleware component or attribute. Secure token and cookie lifecycles, correct CSRF and CORS configuration, generic error messages, strong password handling, complete authorization checks, automated tests and operational monitoring must work together.

Repeat this checklist before every release. Update the threat model whenever a new endpoint, client or claim is introduced. In this way, the Identity and JWT infrastructure built throughout the course becomes more than a working login system: it becomes a reviewable, testable and maintainable foundation for production applications.

Sources