developer tip

OAuth v2에 액세스 및 새로 고침 토큰이 모두있는 이유는 무엇입니까?

optionbox 2020. 10. 3. 10:30
반응형

OAuth v2에 액세스 및 새로 고침 토큰이 모두있는 이유는 무엇입니까?


초안 OAuth 2.0 프로토콜의 섹션 4.2는 권한 부여 서버가 access_token(자원으로 자신을 인증하는 데 사용되는)뿐만 아니라 refresh_token순전히 새를 만드는 데 사용되는를 모두 반환 할 수 있음을 나타냅니다 access_token.

https://tools.ietf.org/html/rfc6749#section-4.2

왜 둘 다 있습니까? 그냥 access_token마지막으로 만들지 않는 이유 refresh_tokenrefresh_token무엇입니까?


새로 고침 토큰의 개념은 액세스 토큰이 손상되면 수명이 짧기 때문에 공격자가이를 악용 할 수있는 제한된 창을 갖는다는 것입니다.

공격자가 액세스 토큰을 얻기 위해 새로 고침 토큰 외에도 클라이언트 ID와 암호를 요구하기 때문에 손상된 경우 새로 고침 토큰은 쓸모가 없습니다.

그런 말을 한 인증 서버와 리소스 서버 모두에 대한 모든 호출이 SSL을 통해 수행되므로, - 그들은 액세스 / 새로 고침 토큰을 요청할 때 원래의 클라이언트 ID와 비밀을 포함하여 - 나는에 관해서는 확실 얼마나 "더 이상이다 액세스 토큰 장기 갱신 토큰 및 클라이언트 ID / 비밀 조합보다 손상 될 수 있습니다.

물론 이것은 인증 및 리소스 서버를 모두 제어하지 않는 구현과 다릅니다.

다음은 새로 고침 토큰의 사용에 대해 설명하는 좋은 스레드입니다. OAuth Archives .

새로 고침 토큰의 보안 목적에 대해 설명하는 위의 인용문 :

토큰 새로 고침 ... 오래 지속되는 access_token 누출 위험을 완화합니다 (안전하지 않은 리소스 서버, 베타 또는 잘못 코딩 된 리소스 서버 앱의 로그 파일에있는 쿼리 매개 변수, access_token을 저장하는 비 https 사이트의 JS SDK 클라이언트 쿠키 등)


Catchdave가 제공 한 토론 링크에는 Dick Hardt가 만든 또 다른 유효한 요점 (원본, 데드 링크) 이 있습니다.이 점은 위에서 언급 한 내용 외에도 여기에서 언급 할 가치가 있다고 생각합니다.

새로 고침 토큰에 대한 기억은 보안 및 취소를위한 것이 었습니다. <...>

취소 : 액세스 토큰이 자체 포함 된 경우 새 액세스 토큰을 발행하지 않음으로써 권한을 취소 할 수 있습니다. 리소스는 액세스 토큰이 유효한지 확인하기 위해 권한 부여 서버를 쿼리 할 필요가 없습니다. 이렇게하면 액세스 토큰 유효성 검사가 간소화되고 여러 권한 부여 서버를 쉽게 확장하고 지원할 수 있습니다. 액세스 토큰이 유효하지만 권한이 취소되는 기간이 있습니다.

실제로 Resource Server와 Authorization Server가 동일한 엔터티이고 사용자와 둘 중 하나 간의 연결이 (보통) 동등하게 안전한 상황에서 새로 고침 토큰을 액세스 토큰과 별도로 유지하는 것은별로 의미가 없습니다.

인용문에서 언급했듯이 새로 고침 토큰의 또 다른 역할은 사용자가 언제든지 액세스 토큰을 취소 할 수 있도록하는 것입니다 (예 : 프로필의 웹 인터페이스를 통해) 동시에 시스템 확장 성을 유지하는 것입니다. .

일반적으로 토큰은 서버 데이터베이스의 특정 레코드를 가리키는 임의의 식별자이거나 자체에 모든 정보를 포함 할 수 있습니다 (예를 들어이 정보는 MAC 로 서명되어야 함 ).

수명이 긴 액세스 토큰이있는 시스템의 작동 방식

서버는 클라이언트가 토큰을 발행하여 미리 정의 된 범위 세트 내에서 사용자의 데이터에 액세스 할 수 있도록합니다. 토큰을 취소 할 수 있도록 유지하려면 "취소됨"플래그가 설정되거나 설정되지 않은 상태로 토큰을 데이터베이스에 저장해야합니다 (그렇지 않으면 자체 포함 된 토큰으로이를 어떻게 수행 할 수 있습니까?). 데이터베이스에는 많은 len(users) x len(registered clients) x len(scopes combination)레코드 가 포함될 수 있습니다. . 그러면 모든 API 요청이 데이터베이스에 도달해야합니다. O (1)을 수행하는 데이터베이스에 쿼리를 수행하는 것은 매우 사소한 일이지만 단일 장애 지점 자체가 시스템의 확장 성과 성능에 부정적인 영향을 미칠 수 있습니다.

장기 갱신 토큰 및 단기 액세스 토큰이있는 시스템의 작동 방식

여기서는 데이터베이스의 해당 레코드가있는 임의 새로 고침 토큰과 만료 타임 스탬프 필드를 포함하는 서명 된 자체 포함 액세스 토큰의 두 가지 키를 발급합니다.

액세스 토큰은 자체 포함되어 있으므로 유효성을 확인하기 위해 데이터베이스에 전혀 액세스 할 필요가 없습니다. 우리가해야 할 일은 토큰을 디코딩하고 서명과 타임 스탬프를 확인하는 것입니다.

그럼에도 불구하고 우리는 여전히 새로 고침 토큰의 데이터베이스를 유지해야하지만이 데이터베이스에 대한 요청 수는 일반적으로 액세스 토큰의 수명에 의해 정의됩니다 (수명이 길수록 액세스 비율이 낮음).

특정 사용자의 클라이언트 액세스를 취소하려면 해당 새로 고침 토큰을 "취소됨"으로 표시 (또는 완전히 제거)하고 새 액세스 토큰 발급을 중지해야합니다. 새로 고침 토큰이 취소되는 기간이 있지만 해당 액세스 토큰은 여전히 ​​유효 할 수 있습니다.

트레이드 오프

새로 고침 토큰은 Access Token 데이터베이스의 SPoF (Single Point of Failure)를 부분적으로 제거하지만 몇 가지 명백한 단점이 있습니다.

  1. 창". "사용자가 액세스를 취소 함"과 "액세스가 취소되도록 보장"이벤트 사이의 시간 프레임.

  2. 클라이언트 로직의 복잡성.

    새로 고침 토큰 없이

    • 액세스 토큰으로 API 요청 보내기
    • 액세스 토큰이 유효하지 않은 경우 실패하고 사용자에게 재 인증을 요청합니다.

    새로 고침 토큰

    • 액세스 토큰으로 API 요청 보내기
    • If access token is invalid, try to update it using refresh token
    • if refresh request passes, update the access token and re-send the initial API request
    • If refresh request fails, ask user to re-authenticate

I hope this answer does make sense and helps somebody to make more thoughtful decision. I'd like to note also that some well-known OAuth2 providers, including github and foursquare adopt protocol without refresh tokens, and seem happy with that.


Despite all the great answers above, I as a security master student and programmer who previously worked at eBay when I took a look into buyer protection and fraud, can say to separate access token and refresh token has its best balance between harassing user of frequent username/password input and keeping the authority in hand to revoke access to potential abuse of your service.

Think of a scenario like this. You issue user of an access token of 3600 seconds and refresh token much longer as one day.

  1. The user is a good user, he is at home and gets on/off your website shopping and searching on his iPhone. His IP address doesn't change and have a very low load on your server. Like 3-5 page requests every minute. When his 3600 seconds on the access token is over, he requires a new one with the refresh token. We, on the server side, check his activity history and IP address, think he is a human and behaves himself. We grant him a new access token to continue using our service. The user won't need to enter again the username/password until he has reached one day life-span of refresh token itself.

  2. The user is a careless user. He lives in New York, USA and got his virus program shutdown and was hacked by a hacker in Poland. When the hacker got the access token and refresh token, he tries to impersonate the user and use our service. But after the short-live access token expires, when the hacker tries to refresh the access token, we, on the server, has noticed a dramatic IP change in user behavior history (hey, this guy logins in USA and now refresh access in Poland after just 3600s ???). We terminate the refresh process, invalidate the refresh token itself and prompt to enter username/password again.

  3. The user is a malicious user. He is intended to abuse our service by calling 1000 times our API each minute using a robot. He can well doing so until 3600 seconds later, when he tries to refresh the access token, we noticed his behavior and think he might not be a human. We reject and terminate the refresh process and ask him to enter username/password again. This might potentially break his robot's automatic flow. At least makes him uncomfortable.

You can see the refresh token has acted perfectly when we try to balance our work, user experience and potential risk of a stolen token. Your watch dog on the server side can check more than IP change, frequency of api calls to determine whether the user shall be a good user or not.

Another word is you can also try to limit the damage control of stolen token/abuse of service by implementing on each api call the basic IP watch dog or any other measures. But this is expensive as you have to read and write record about the user and will slow down your server response.


Neither of these answers get to the core reason refresh tokens exist. Obviously, you can always get a new access-token/refresh-token pair by sending your client credentials to the auth server - thats how you get them in the first place.

So the sole purpose of the refresh token is to limit the use of the client credentials being sent over the wire to the auth service. The shorter the ttl of the access-token, the more often the client credentials will have to be used to obtain a new access-token, and therefore the more opportunities attackers have to compromise the client credentials (although this may be super difficult anyway if asymmetric encryption is being used to send them). So if you have a single-use refresh-token, you can make the ttl of access-tokens arbitrarily small without compromising the client credentials.


To clear up some confusion you have to understand the roles of the client secret and the user password, which are very different.

The client is an app/website/program/..., backed by a server, that wants to authenticate a user by using a third-party authentication service. The client secret is a (random) string that is known to both this client and the authentication server. Using this secret the client can identify itself with the authentication server, receiving authorization to request access tokens.

To get the initial access token and refresh token, what is required is:

  • The user ID
  • The user password
  • The client ID
  • The client secret

To get a refreshed access token however the client uses the following information:

  • The client ID
  • The client secret
  • The refresh token

This clearly shows the difference: when refreshing, the client receives authorization to refresh access tokens by using its client secret, and can thus re-authenticate the user using the refresh token instead of the user ID + password. This effectively prevents the user from having to re-enter his/her password.

This also shows that losing a refresh token is no problem because the client ID and secret are not known. It also shows that keeping the client ID and client secret secret is vital.


This answer is from Justin Richer via the OAuth 2 standard body email list. This is posted with his permission.


The lifetime of a refresh token is up to the (AS) authorization server — they can expire, be revoked, etc. The difference between a refresh token and an access token is the audience: the refresh token only goes back to the authorization server, the access token goes to the (RS) resource server.

Also, just getting an access token doesn’t mean the user’s logged in. In fact, the user might not even be there anymore, which is actually the intended use case of the refresh token. Refreshing the access token will give you access to an API on the user’s behalf, it will not tell you if the user’s there.

OpenID Connect doesn’t just give you user information from an access token, it also gives you an ID token. This is a separate piece of data that’s directed at the client itself, not the AS or the RS. In OIDC, you should only consider someone actually “logged in” by the protocol if you can get a fresh ID token. Refreshing it is not likely to be enough.

For more information please read http://oauth.net/articles/authentication/


Clients can be compromised in many ways. For example a cell phone can be cloned. Having an access token expire means that the client is forced to re-authenticate to the authorization server. During the re-authentication, the authorization server can check other characteristics (IOW perform adaptive access management).

Refresh tokens allow for a client only re-authentication, where as re-authorize forces a dialog with the user which many have indicated they would rather not do.

Refresh tokens fit in essentially in the same place where normal web sites might choose to periodically re-authenticate users after an hour or so (e.g. banking site). It isn't highly used at present since most social web sites don't re-authenticate web users, so why would they re-authenticate a client?


To further simplify B T's answer: Use refresh tokens when you don't typically want the user to have to type in credentials again, but still want the power to be able to revoke the permissions (by revoking the refresh token)

You cannot revoke an access token, only a refresh token.


Why not just make the access_token last as long as the refresh_token and not have a refresh_token?

In addition to great answers other people have provided there is another reason why would use refresh tokens and its to do with claims.

Each token contains claims which can include anything from the users name, their roles or the provider which created the claim. As a token is refreshed these claims are updated.

If we refresh the tokens more often we are obviously putting more strain on our identity services however we are getting more accurate and up-to-date claims.


Assume you make the access_token last very long, and don't have refresh_token, so in one day, hacker get this access_token and he can access all protected resources!

But if you have refresh_token, the access_token's live time is short, so the hacker is hard to hack your access_token because it will be invalid after short period of time. Access_token can only be retrieved back by using not only refresh_token but also by client_id and client_secret, which hacker doesn't have.


While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation. Another point missing in discussion is from rfc6749#page-55

"For example, the authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response.The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.


This answer has been put together by the help of two senior devs (John Brayton and David Jennes).

The main reason to use a refresh token is to reduce the attack surface.

Let's suppose there is no refresh key and let’s go through this example:

A building has 80 doors. All doors are opened with the same key. The key changes every 30 minutes.

If I’m the hacker and get your key, then at the end of the 30 minutes, I’ll courier that to the keymaker and get a new key. I’ll be able to continuously open all doors regardless of the key changing.

Question: During the 30 minutes, how many hacking opportunities did I have against the key? I had 80 hacking opportunities, each time you used the key (think of this as making a network request and passing the access token to identify yourself). So that’s 80X attack surface.

Now let’s go through the same example but this time let’s assume there’s a refresh key.

A building has 80 doors. All doors are opened with the same key. The key changes every 30 minutes. If I’m the hacker and get your key, I can use it for 30 minutes, but at the end of the 30 minutes sending it to the keymaker has no value. If I do, then the keymaker would just say this key is expired. To be able to extend my hack I would have to hack the courier to the keymaker. The courier has a distinct key (think of this as a refresh token).

Question: During the 30 minutes, how many hacking opportunities did I have against the courier? 80? No. I only had 1 hacking opportunity. During the time the courier communicates with the keymaker. So that’s 1X attack surface. I did have 80 hacking opportunities against the key, but they are no good after 30 minutes.


A server would verify an access token based on credentials and signing of (typically) a JWT.

An access token leaking is bad, but once it expires it is no longer useful to an attacker. A refresh token leaking is far worse, but presumably it is less likely. (I think there is room to question whether the likelihood of a refresh token leaking is much lower than that of an access token leaking, but that’s the idea.)

Point is that the access token is added to every request you make, whereas a refresh token is only used during the refresh flow So less chance of a MITM seeing the token

Frequency helps an attacker. Heartbleed-like potential security flaws in SSL, potential security flaws in the client, and potential security flaws in the server all make leaking possible.

In addition, if the authorization server is separate from the application server processing other client requests then that application server will never see refresh tokens. It will only see access tokens that will not live for much longer.

Compartmentalization is good for security.


What refresh token is NOT about?

The ability to update/revoke access level through refresh tokens is a byproduct of choosing to use refresh tokens, otherwise a standalone access token could be revoked or have its access level modified when it expires and users gets a new token”


Let's consider a system where each user is linked to one or more roles and each role is linked to one or more access privileges. This information can be cached for better API performance. But then, there may be changes in the user and role configurations (for e.g. new access may be granted or current access may be revoked) and these should be reflected in the cache.

We can use access and refresh tokens for such purpose. When an API is invoked with access token, the resource server checks the cache for access rights. IF there is any new access grants, it is not reflected immediately. Once the access token expires (say in 30 minutes) and the client uses the refresh token to generate a new access token, the cache can be updated with the updated user access right information from the DB.

In other words, we can move the expensive operations from every API call using access tokens to the event of access token generation using refresh token.


First, the client authenticates with the authorization server by giving the authorization grant.

Then, the client requests the resource server for the protected resource by giving the access token.

The resource server validates the access token and provides the protected resource.

The client makes the protected resource request to the resource server by granting the access token, where the resource server validates it and serves the request, if valid. This step keeps on repeating until the access token expires.

If the access token expires, the client authenticates with the authorization server and requests for a new access token by providing refresh token. If the access token is invalid, the resource server sends back the invalid token error response to the client.

The client authenticates with the authorization server by granting the refresh token.

The authorization server then validates the refresh token by authenticating the client and issues a new access token, if it is valid.

참고URL : https://stackoverflow.com/questions/3487991/why-does-oauth-v2-have-both-access-and-refresh-tokens

반응형