OAuth is an open standard for secure authentication, commonly used to grant websites or applications access to information on other platforms without giving them the passwords.
OAuth是安全身份验证的开放标准,通常用于授予网站或应用程序访问其他平台上的信息的权限,而无需为其提供密码。
This article shows the technical implementation of an OAuth2 Authentication on Android, using the Authorization Code Flow. It uses Twitch as OAuth Provider but it can be applied to any other API following the OAuth2 standard.
本文使用授权代码 流展示了Android上OAuth2身份验证的技术实现。 它使用Twitch作为OAuth Provider,但可以将其应用于遵循OAuth2标准的 任何其他API 。
To learn about the structure and reasoning behind the OAuth standard please check out this great post by Takahiko Kawasaki.To learn about all the different OAuth2 Authorization Flows and its steps check out this awesome article by that same author.
要了解OAuth标准背后的结构和推理,请查看Takahiko Kawasaki的 精彩文章 。要了解所有不同的OAuth2 授权流程及其步骤, 请查看同一位作者的精彩文章 。
总览 (Overview)
This Article is divided into the following parts:
本文分为以下几部分:
Obtain an authorization code from the OAuth provider using a WebView.
使用WebView从OAuth提供程序获取授权代码 。
Use the previous code to obtain the access token and refresh token with a networking library (Ktor).
使用前面的代码来获取访问令牌并使用网络库( Ktor ) 刷新令牌 。
- [Recurring]: When the access token expires, use the refresh token to obtain a new one, or redirect the user to step 1. [重复出现]:当访问令牌过期时,请使用刷新令牌来获取一个新令牌,或者将用户重定向到步骤1。
第1部分。获取授权码 (Part 1. Getting the Authorization Code)
The authorization code is obtained through a URL request that can be used in any regular browser.
授权代码是通过可在任何常规浏览器中使用的URL请求获得的。
First, prepare the different parameters needed, then build the URL and finally catch the redirect inside the WebView.
首先,准备所需的不同参数,然后构建URL,最后在WebView中捕获重定向。