Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
First identify how the site protects the page. For a cookie-based website session, use one cookie-enabled HttpClient handler for both login and later requests. For a bearer-protected API, obtain an access token through the provider’s supported OAuth or OpenID Connect (OIDC) flow and send it in the Authorization: Bearer header. A 401 usually means authentication is missing or invalid; a 403 means the authenticated identity lacks permission.
Identify the authentication scheme before making a request
“Secured page” can mean a website that creates a session cookie after login, an API that accepts access tokens, or a server configured for another scheme such as Basic or Windows authentication. These methods are not interchangeable. Sending a password as a form field will not satisfy an API expecting a bearer token, and a bearer token will not automatically establish a browser-style cookie session.
Use the service’s documentation or administrator-provided instructions to determine the expected scheme, login endpoint, scopes or roles, and whether interactive steps are required. For a server that issues challenges, inspect the response’s WWW-Authenticate header. Only send credentials using the scheme the service explicitly supports, over HTTPS.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
| Approach | Typical use | Credential persistence |
|---|---|---|
| Cookie session | A website login followed by requests to pages in the same session | Keep cookies in a CookieContainer and reuse its handler |
| Bearer token | An API protected by OAuth/OIDC access tokens | Use the identity provider’s supported token cache or secure server-side storage |
| Basic or Windows authentication | Only a server or deployment that explicitly requires that scheme | Follow that service’s credential-handling guidance |
Access a cookie-protected page with HttpClient
A browser retains cookies between requests to a site. A non-browser C# client must do that deliberately. Attach a CookieContainer to an HttpClientHandler, use the same client for the documented login request and the protected page request, and do not replace the handler between them.
#1 Best Overall
Example: post a documented login form, then request a page
This example shows the session pattern; /login, the form field names, and the protected path are illustrative. Replace them with the site’s documented values. The site may also require an antiforgery token, a preliminary page request, redirects, MFA, or a consent step.
The code targets modern .NET and requires System.Net, System.Net.Http, and System.Collections.Generic. Put credentials in configuration or a secret store rather than hard-coding them.
using System.Net;
using System.Net.Http;
using System.Collections.Generic;
var cookies = new CookieContainer();
using var handler = new HttpClientHandler
{
CookieContainer = cookies,
UseCookies = true,
AllowAutoRedirect = true
};
using var client = new HttpClient(handler)
{
BaseAddress = new Uri("https://example.com")
};
var userName = Environment.GetEnvironmentVariable("SITE_USERNAME")
?? throw new InvalidOperationException("Set SITE_USERNAME.");
var password = Environment.GetEnvironmentVariable("SITE_PASSWORD")
?? throw new InvalidOperationException("Set SITE_PASSWORD.");
using var login = await client.PostAsync("/login",
new FormUrlEncodedContent(new Dictionary<string, string>
{
["username"] = userName,
["password"] = password
}));
login.EnsureSuccessStatusCode();
using var page = await client.GetAsync("/secure/page");
page.EnsureSuccessStatusCode();
var html = await page.Content.ReadAsStringAsync();
Console.WriteLine(html);
After a successful cookie login, ASP.NET Core Identity’s documented behavior is that the authentication cookie is automatically sent with the request and the endpoint is authorized. In a non-browser client, the cookie container supplies the equivalent persistence for subsequent requests made through that handler.
Rank #2
What to adapt for the real site
- Form names and endpoint: use the exact route and field names specified by the application. Some sites do not expose a form-based login endpoint for clients.
- Antiforgery/CSRF protection: a site may require retrieving a login page first, extracting a token, and submitting it alongside the credentials. Implement the documented protocol; do not omit or bypass the protection.
- Redirects: an automatic redirect can land on a login page while appearing superficially successful. Check the final response URI and content when the expected protected content is absent.
- Interactive identity steps: if login requires MFA, consent, or a browser-mediated OIDC flow, do not try to simulate or evade the control with a guessed form post. Use the supported interactive flow.
Call a bearer-protected API with an access token
For a bearer-protected API, the client sends the access token in the HTTP authorization header. Token acquisition is a separate step: use the identity provider’s supported flow or official library, then attach the resulting access token to the API request.
using System.Net.Http;
using System.Net.Http.Headers;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
using var response = await client.GetAsync(
"https://api.example.com/secure-resource");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
accessToken must be a valid token for the target API and its expected audience and permissions. Do not log it, put it in a URL, or embed confidential client secrets in a desktop or browser-distributed application. Use the provider’s library or a secure server-side cache for acquisition, caching, and refresh.
Choose the flow based on who the application represents
- Delegated user access: when the app acts on behalf of a signed-in person, use the provider’s supported OIDC/OAuth interactive flow. Microsoft’s guidance recommends authorization code with PKCE for delegated access; web applications use the confidential code flow with PKCE.
- Application-only access: for an unattended service with no user, use OAuth client credentials if the API and identity provider support it. The service needs the permissions granted for that application.
The API validates the token and its claims. The caller’s job is to acquire the appropriate token and present it using the expected scheme; possession of any token is not by itself proof that it grants access to the requested resource.
Use Basic or Windows authentication only when required
Some servers explicitly require Basic or Negotiate/Windows authentication and may advertise a challenge in WWW-Authenticate. Follow the server operator’s instructions and send credentials only over HTTPS. Do not assume these schemes are substitutes for OAuth/OIDC, or that a site’s browser login can be reproduced by adding an Authorization header. For modern APIs, prefer the OAuth/OIDC method the service documents.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteDiagnose 401, 403, redirects, and browser-only success
401 Unauthorized
The request is not authenticated as expected: credentials may be absent, invalid, expired, sent using the wrong scheme, or intended for a different audience. Check the WWW-Authenticate challenge, verify the token or cookie is being sent to the correct host, and acquire or refresh the credential through the supported mechanism.
403 Forbidden
The server has authenticated the caller but does not permit the requested action. Check the account’s authorization, roles, policy, and—when using tokens—the granted scopes and claims. Repeating the same request with the same credential will not grant missing permissions.
Rank #4
302 redirect to a login page
A cookie-authenticated website may redirect an unauthenticated request to its login page. Inspect the redirect target and the final response rather than treating a successful redirect as proof of authorization. Confirm that login actually succeeded and that the same cookie-enabled handler made the protected request.
The browser works, but C# does not
A browser may have completed steps the C# client has not: cookies, CSRF checks, redirects, MFA, consent, or an interactive OIDC callback. Compare the documented protocol and request details, and implement the supported flow. Do not scrape credentials from a browser profile or bypass access controls.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Or skip the browser setup
For a public page that only needs a screenshot, ScreenshotNeo is a website screenshot API rather than a replacement for authenticating an application’s own HttpClient requests. Its capture options include custom headers, cookies, and Authorization, but use those only when you are authorized to access the target and have a supported way to provide its credentials. One request can return an image or PDF; this example saves a WebP screenshot of a public URL.
Best Value
See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.
Sign up for 1,000 free screenshots a month with no card.
Security and reliability checklist
- Use HTTPS and the authentication scheme explicitly required by the target.
- Keep cookie handlers alive for the required session lifetime, but avoid sharing authenticated clients across unrelated users or accounts.
- Keep access tokens, passwords, and confidential client credentials out of source code, logs, and URLs.
- Account for token expiration, refresh, and the correct API audience using the identity provider’s supported library.
- Keep certificate validation enabled. Do not disable TLS checks to make an authentication error disappear.
- Distinguish authorization failures from transient network or server failures before retrying. Repeatedly submitting passwords or expired tokens is not a fix for missing permissions.
Frequently Asked Questions
Can I access a page that requires MFA from a C# program?
Use the service’s supported interactive sign-in or delegated OAuth/OIDC flow. Do not try to bypass MFA by replaying a browser session or guessing a form endpoint.
Should I put a bearer token in the URL?
No. Send it in the Authorization header and protect it as a secret; URLs are more likely to be retained in logs and other records.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

