واجهة برمجة تطبيقات البريد الإلكتروني لـ OAuth: لماذا انتهى الوصول إلى كلمة المرور وما الذي سيأتي بعد ذلك
كلمات مرور البريد الإلكتروني تنتهي.
محتويات
If you own an integration that reads or sends from user inboxes, the OAuth email API is no longer a modernisation project you can defer. Password-based access to Gmail and Outlook mailboxes has already been switched off for most protocols, and the last remaining Basic-auth path at Microsoft, SMTP client submission, now has a published end date. What is left is an OAuth 2.0 flow per provider, with provider-specific scope rules, token lifetimes and notification models that behave differently enough to break naive implementations.
This is a practitioner's map of what actually changed, what the current deadlines are, and the operational details that separate an integration that survives contact with production from one that starts silently disconnecting users. If you would rather not maintain two provider stacks yourself, an oauth email api abstracts the differences behind one flow, but you still need to understand what it is abstracting.
Why Password-Based Mailbox Access Ended
For most of email's history the auth model was simple: the user handed your app a password, you opened an IMAP or SMTP connection, and you stored that password somewhere. Email protocols predate modern identity standards by decades, so there was nothing else to use. Two forces killed it.
The first was two-factor authentication. Once a user enables 2FA, an account password stops working over IMAP. Providers patched around this with app passwords, but those are awkward to generate, invisible to most users, and they leave the credential-storage problem entirely with you. Google still issues app passwords, but only for accounts with 2-Step Verification enabled, never for accounts enrolled in Advanced Protection or using security keys as their only second factor, and a Workspace administrator can block them outright.
The second was breach economics. A stored mailbox password, or an app password, is a credential of full power with no expiry. One database compromise exposes every connected mailbox at once. OAuth replaces that with a short-lived access token plus a refresh token that the user, the provider or an administrator can revoke independently, at any time, without changing the account password.
The Real Deprecation Timeline
Both providers moved in stages, and the dates matter because several widely repeated summaries are now out of date.
| Provider and Surface | What Changed | Status |
|---|---|---|
| Exchange Online: EAS, POP, IMAP, EWS, RPS, OAB, Autodiscover | Basic authentication disabled | Done. Applied to most cloud environments on 1 October 2022 and now disabled in all tenants, with no way for anyone to re-enable it |
| Outlook.com personal accounts (IMAP, POP, SMTP) | Basic authentication withdrawn from third-party mail apps | Done, 16 September 2024 |
| Exchange Online: SMTP AUTH client submission | Basic authentication retirement | Usable through 31 December 2026; disabled by default for existing tenants from January 2027, with admin re-enablement still possible; final removal date to be announced in the second half of 2027 |
| Google Workspace: IMAP, POP, CalDAV, CardDAV, Google Sync | Less secure apps (password-only sign-in) withdrawn | Admin console control removed 15 June 2024; password-only third-party access no longer supported for Workspace accounts |
Note the correction on Microsoft: an earlier plan would have started rejecting a percentage of SMTP AUTH submissions on 1 March 2026 and reached full rejection by 30 April 2026. Microsoft scrapped that schedule, citing customers with legacy workflows such as multi-function printers whose vendors had not shipped OAuth support. The extension is real, but the direction is unchanged and the re-enablement switch after January 2027 is explicitly temporary.
What the OAuth Flow Looks Like End to End
The shape is identical across providers; the details are not.
- Redirect the user to the provider's authorisation endpoint. Google uses accounts.google.com/o/oauth2/v2/auth; Microsoft uses login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize. Every parameter in that query string needs correct escaping, and a mismatched redirect_uri is the most common first-day failure; a URL encoder settles the question in seconds rather than through trial and error.
- The user reviews the requested scopes and grants or denies consent.
- The provider redirects back with an authorisation code and the state value you sent. Generate that state as an unguessable random value per request; a UUIDv4 generator is fine for scaffolding one while you build the flow.
- Exchange the code server-side for an access token and refresh token. This call must never happen in the browser.
- Call the provider API with the access token — the Gmail API, Microsoft Graph, or IMAP and SMTP using SASL XOAUTH2.
- Refresh before expiry, not after failure. Detect the expiry window and renew proactively.
For the IMAP and SMTP path, the XOAUTH2 credential is a base64 string of the form base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A"), where ^A is the Control-A character (0x01). Almost every XOAUTH2 bug is a malformed separator or a stale token baked into the string, and decoding the value you actually sent with a Base64 decoder is the fastest way to see which.
Microsoft Protocol Scopes You Will Actually Use
For delegated (per-user) access to Exchange Online over legacy protocols, the permission strings are https://outlook.office.com/IMAP.AccessAsUser.All, https://outlook.office.com/POP.AccessAsUser.All and https://outlook.office.com/SMTP.Send. For app-only access via the client credentials flow, the equivalents are IMAP.AccessAsApp, POP.AccessAsApp and SMTP.SendAsApp, requested against the resource https://outlook.office365.com/.default. Mixing the delegated and application forms is a frequent cause of consent screens that appear to succeed and tokens that then fail at the protocol layer.
Gmail Scopes: Get the Classification Right
Google sorts scopes into non-sensitive, sensitive and restricted, and the boundary is not where most teams assume it is. Getting this wrong changes your launch timeline by months.
| Gmail Scope | Classification | What It Grants |
|---|---|---|
| gmail.labels | Non-sensitive | See and edit email labels |
| gmail.send | Sensitive | Send email on the user's behalf |
| gmail.metadata | Restricted | Labels and headers, but not message bodies |
| gmail.readonly | Restricted | View email messages and settings |
| gmail.compose | Restricted | Manage drafts and send email |
| gmail.modify | Restricted | Read, compose and send, without permanent deletion |
| mail.google.com | Restricted | Full mailbox access including permanent deletion |
Two things fall out of that table. Send-only integrations sit in sensitive territory rather than restricted, which is a materially lighter review path, so a product that only needs to send should never request gmail.modify out of convenience. And metadata access is restricted despite never touching message bodies, which surprises teams building analytics on headers alone.
Security Assessment for Restricted Scopes
Restricted scopes require a security assessment under the CASA framework, which is built on the OWASP Application Security Verification Standard. Google works in assurance levels rather than the three numbered tiers people still quote: AL1 and AL2, with the level assigned from your user count, the scopes you request and other application signals. Once an app reaches AL2 it stays at AL2 in later years, and every app must be revalidated at least every twelve months. The older CASA self-scanning route has been deprecated, so plan for an authorised assessor rather than a self-service scan.
Google does not publish assessment pricing; the fee comes from the assessor, so budget by quoting two or three of them rather than by copying a number off a blog. What consistently causes failures is unremarkable: thin logging, weak token storage, no documented retention or deletion process, and a privacy policy that does not say what you actually do with mailbox data. If your published policy is stale, regenerating a baseline with a privacy policy generator and then editing it to match your real data flows is faster than writing one from a blank page.
Token Lifetimes and the Failures They Cause
Refresh tokens are close in value to the user's password and behave differently on each platform. These are the documented rules worth designing around.
| Behaviour | Microsoft Entra ID | |
|---|---|---|
| Access token lifetime | Limited; treat roughly an hour as the planning figure | Randomised 60–90 minutes, averaging 75; 24–28 hours where Continuous Access Evaluation applies |
| Refresh token idle expiry | Expires after six months of non-use | Maximum inactive time of 90 days |
| Refresh token maximum age | No fixed age, but subject to the conditions below | Until revoked |
| Pre-launch trap | Apps with an external consent screen still in Testing status get refresh tokens that expire in 7 days | Refresh and session lifetimes are not configurable; use Conditional Access sign-in frequency instead |
| Hard per-account limit | 100 refresh tokens per Google Account per OAuth client ID | Governed by tenant policy rather than a per-client token count |
Two of these bite in production. A Google password change revokes refresh tokens that carry Gmail scopes, so a routine user password reset shows up in your system as an authentication failure you did not cause and cannot prevent. And the 100-token ceiling per account per client means that issuing a fresh token on every reconnect silently evicts the oldest ones; reuse tokens instead of minting new ones on each sign-in.
Storage rules follow from that value. Encrypt at rest with a KMS-managed key and use envelope encryption, so the database holds an encrypted token and an encrypted data key while the master key never leaves the KMS. Rotate keys on a schedule. Make every read of a refresh token outside the normal refresh path auditable. Refresh proactively, five to ten minutes ahead of expiry. And when a refresh is rejected, surface a reconnect prompt to the user rather than retrying into a loop.
Real-Time Notifications Without Polling
Tokens get you access; notifications get you a responsive product. The two providers differ more here than anywhere else.
Gmail pushes through Google Cloud Pub/Sub. You create a topic and a subscription, grant publish rights to the service account gmail-api-push@system.gserviceaccount.com, and receive notifications carrying the user's address and a new historyId, which you then resolve with history.list. The critical operational detail is renewal: you must call watch at least once every 7 days per user or notifications stop, and Google recommends calling it once per day. Build that as a daily job from the outset, not as a fix after your first silent outage.
Microsoft Graph uses subscription resources. For Outlook message, event and contact resources the maximum expiration is 10,080 minutes, just under 7 days, and it drops to 1,440 minutes, under one day, for rich notifications that include resource data. A mailbox permits at most 1,000 active subscriptions across all applications. Creating a subscription requires answering a validation handshake, and every notification should be checked against the clientState you registered; an HMAC generator is useful when you are working out the signature check for encrypted resource-data payloads.
Plain IMAP has no push at all. IMAP IDLE holds an open connection per mailbox, which is workable for hundreds of users and painful for hundreds of thousands.
Migrating a Legacy Integration
If you still have password-based connections in production, work in this order.
- Inventory every connection by provider, protocol and auth method. You cannot plan a cutover against an unknown denominator.
- Move Microsoft SMTP submission first. It is the only Basic-auth path still alive and it has a date on it.
- Register the app and request the narrowest scopes that support your features, using the delegated or application permissions listed above.
- Verify connectivity before you migrate users. Confirming that the new credentials and endpoints work with an SMTP tester separates transport problems from token problems while both are still cheap to fix.
- Add a reconnect flow that triggers OAuth ahead of legacy failure, so users re-consent on your schedule rather than at the moment their mail stops syncing.
- Retire the legacy code path once usage falls to a residual level, and remove the stored credentials rather than leaving them in the database.
Throughout, you will be reading token responses, error bodies and notification payloads by hand; piping them through a JSON formatter makes an invalid_grant far easier to diagnose than squinting at a single-line response in a log.
Frequently Asked Questions
Is Basic authentication completely dead at Microsoft?
Almost. Basic auth is disabled across Exchange Online for Exchange ActiveSync, POP, IMAP, EWS, Remote PowerShell, Offline Address Book, Autodiscover and the Outlook desktop clients, and it cannot be re-enabled by anyone. SMTP AUTH client submission is the exception: it remains usable through 31 December 2026, is disabled by default for existing tenants from January 2027 with temporary admin re-enablement, and Microsoft will announce the final removal date in the second half of 2027.
Do I need a CASA assessment just to send email from Gmail?
No. The gmail.send scope is classified as sensitive, not restricted, so a send-only integration avoids the restricted-scope security assessment. The moment you add gmail.readonly, gmail.compose, gmail.modify, gmail.metadata or mail.google.com, you are in restricted territory and the assessment applies.
How long do Microsoft Graph mailbox subscriptions last?
Outlook message, event and contact subscriptions can be created with a maximum expiration of 10,080 minutes, just under seven days. Subscriptions that include resource data in the notification are capped at 1,440 minutes, under one day. Renew before expiry, and remember the ceiling of 1,000 active subscriptions per mailbox across all applications.
Why do my Gmail refresh tokens keep expiring after a week?
Because your OAuth consent screen is configured for external users and the project is still in Testing publishing status. Google issues refresh tokens that expire in 7 days in that state, unless the only scopes requested are a subset of name, email address and user profile. Publishing the app resolves it.
What happens to my tokens when a user changes their password?
On Google, a password change revokes refresh tokens that contain Gmail scopes, so the connection breaks through no fault of your code. Detect the failure, mark the connection as needing attention, and prompt the user to reconnect. Treat this as a normal lifecycle event with its own UI, not as an error condition.
Can I still use app passwords instead of migrating?
It is a dead end. Google issues app passwords only to accounts with 2-Step Verification, withholds them from Advanced Protection enrollees and security-key-only setups, and lets Workspace administrators disable them. They also leave you storing a full-power credential, which is precisely the liability OAuth removes.
Treat OAuth as Architecture, Not a Checkbox
The teams that handle this well decide their scope set before writing the consent screen, build proactive token refresh and a reconnect path in the first iteration, and schedule notification renewal as a job rather than discovering the 7-day limits in an incident. The teams that struggle treat OAuth as a login button and then spend a quarter chasing silent disconnections whose root cause is a documented expiry rule.
None of the constraints above are secret. They are published by Google and Microsoft, they change on announced schedules, and they are cheap to design around when you read them first. Inspecting response headers with an HTTP header parser while you build costs minutes; retrofitting token hygiene into a live integration after an assessment failure costs a release cycle.
The UrwaTools Editorial Team delivers clear, practical, and trustworthy content designed to help users solve problems efficiently. Our articles focus on accurac...