Токены обновления и области доступа
Узнайте о токенах обновления, позволяющих получать новые токены доступа без повторной аутентификации, и о роли областей доступа в определении разрешений.
«Токены обновления и области доступа» — бесплатный урок OAuth2 & OpenID Connect Deep Dive на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения OAuth2 & OpenID Connect Deep Dive, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс OAuth2 & OpenID Connect Deep Dive содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Keep Your Apps Authorized
Imagine using an app that needs to access your online photos. It gets permission, but what if that permission expires after just an hour?
You'd have to log in again and grant permission every single time! That's not a great user experience, is it?
The Short Life of Access Tokens
Access tokens are like temporary keys. They grant access to specific resources (like your photos) for a short time, often minutes or hours.
This short lifespan is a crucial security feature. If an access token is stolen, an attacker has a limited window to use it, reducing potential damage.
Introducing Refresh Tokens
To solve the constant re-login problem, OAuth2 uses refresh tokens. Think of them as a special, long-term key.
An application uses a refresh token to quietly request a brand new access token from the Authorization Server without needing you to re-enter your credentials.
The Refresh Process
When your access token expires, the client application sends its refresh token to the Authorization Server. This happens in the background.
If the refresh token is valid, the server issues a new access token (and sometimes a new refresh token too!). Your app continues working seamlessly.
public class RefreshExample {
public static void main(String[] args) {
System.out.println("1. Access token expires.");
System.out.println("2. Client sends refresh token.");
System.out.println("3. Authorization Server validates.");
System.out.println("4. New access token issued.");
System.out.println("5. App continues without re-login.");
}
}Protecting Refresh Tokens
Since refresh tokens can grant new access tokens, they are very powerful and must be protected carefully. They are more sensitive than access tokens.
- Store securely: Encrypt them or keep them in secure, HTTP-only cookies.
- Revoke: If compromised, they must be immediately revoked by the user or server.
- Limited use: Some systems issue new refresh tokens with each refresh, invalidating the old one.
What Are Scopes?
Now let's talk about scopes. Scopes are simple strings that define the exact permissions an application is requesting from you.
They control *what* an application can do with your resources once it has an access token. Think of them as permission labels, like 'read_email' or 'write_photos'.
How Scopes are Applied
When an app asks for your permission (during the authorization step), it will explicitly list the scopes it needs.
You, the resource owner, then decide which of those permissions to grant. For example, you might grant 'read_profile' but deny 'write_posts'.
Practical Scope Examples
Scopes are typically defined by the Resource Server, and their names can vary. Here are some common examples you might encounter:
openid: Requesting basic identity info (often used in OpenID Connect).profile: Access to your basic profile data (name, picture, etc.).email: Access to your primary email address.https://www.googleapis.com/auth/photos.readonly: Read-only access to Google Photos.
Scopes Persist on Refresh
When an application uses a refresh token to get a new access token, the new access token will generally carry the same scopes that were originally granted.
The application can't magically gain new permissions during a refresh; it must request them again through a full user authorization flow if it needs more access.
Quick Check: Tokens & Scopes
Which of the following statements about Refresh Tokens and Scopes are TRUE?
Summary: Refresh & Scopes
We've covered two vital OAuth2 concepts that enhance both security and user experience:
- Refresh Tokens: Long-lived credentials used to obtain new, short-lived access tokens without user interaction, improving UX.
- Scopes: Granular permissions that define what an application is authorized to do on a user's behalf.
Understanding these helps you build more secure and user-friendly applications!
Часто задаваемые вопросы
Урок «Токены обновления и области доступа» бесплатный?
Да — полный текст урока «Токены обновления и области доступа» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс OAuth2 & OpenID Connect Deep Dive, подпишись на CoddyKit PRO. Курс OAuth2 & OpenID Connect Deep Dive содержит 4 уроков всего.
Чему я научусь в уроке «Токены обновления и области доступа»?
Узнайте о токенах обновления, позволяющих получать новые токены доступа без повторной аутентификации, и о роли областей доступа в определении разрешений. Ты практикуешь OAuth2 & OpenID Connect Deep Dive с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать OAuth2 & OpenID Connect Deep Dive?
Предыдущий опыт не требуется. OAuth2 & OpenID Connect Deep Dive на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Токены обновления и области доступа»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке OAuth2 & OpenID Connect Deep Dive?
Да. Каждый урок OAuth2 & OpenID Connect Deep Dive включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- PKCE для публичных клиентов
- Токены обновления и области доступа
- Учётные данные владельца ресурса
- Обмен токенами (RFC 8693)