- Add GitHub Login to an Android App
- adriantache/GitHubExplorer
- Explore repositories and download files. Contribute to adriantache/GitHubExplorer development by creating an account on…
- GitHub API v3
- Get started with one of our guides, or jump straight into the API documentation.
- Getting Public Repos
- Getting Private Repos (Basic Authentication)
- Getting Private Repos (Two Factor Authentication — OAuth2 Token)
- Android Studio не может войти в GitHub
- 16 ответов
- Creating a personal access token
- In this article
- How to add GitHub Login button to your Android app using Kotlin
- Let’s get started!
- Adding the dependencies
- Creating the GitHub Login Button
Add GitHub Login to an Android App
Or how I figured out dealing with incomplete documentation
I’m currently searching for a job as a Mobile Developer in the Geneva area so I’m applying to all sorts of positions and companies. One of them asked me to make a simple app that can browse a user’s repositories on GitHub, including authentication so you can see your own private repos (did you know we now have unlimited private repos for free on GitHub!). Here’s the finished code if you just want to have a look, but otherwise read on to see the necessary steps:
adriantache/GitHubExplorer
Explore repositories and download files. Contribute to adriantache/GitHubExplorer development by creating an account on…
I have to preface this by saying that before this assignment I really had no idea how to use OAuth and I’ve only sent simple GET requests to APIs. I’m sure that for some people this article is just a whole lot of duh! but for me it was a learning experience and so I wanted to share it.
The first thing I did to start this app was, of course, to consult the GitHub API documentation:
GitHub API v3
Get started with one of our guides, or jump straight into the API documentation.
The documentation exposes two main endpoints to get a list of repos:
So let’s start with the simple use case:
Getting Public Repos
This is as easy as making a get request to the API and decoding the response. I’ve used OKHTTP inside an AsyncTask to make the request and then I simply decode it into an ArrayList of repo names (code is shortened and simplified):
Getting Private Repos (Basic Authentication)
In order to get private repos we have to log in, of course. And this is where the confusion started for me. The documentation talks a lot about OAuth2 and tokens and secrets and the only examples they give are using curl . So I started searching the documentation and then online and lo and behold, Basic Authentication is a technical term! To summarize, basic authentication is essentially sending an Authorization header which contains the string Basic followed by a base64 encode of
So here’s how the code changes:
As you can see, not much changes, we simply change the endpoint and add that authorization header.
Getting Private Repos (Two Factor Authentication — OAuth2 Token)
This is where things get a bit more complex. The process itself isn’t too complicated once you understand how it works, which is like this: if 2FA is active, when you try to log in using basic authentication the API returns a 401 response and the error message Must specify two-factor authentication OTP code. At that point, if SMS 2FA is active, the platform should send out a OTP SMS to the user containing the code. Please note, however, that SMS 2FA for GitHub is finicky and might not work at all in some countries!
So to detect that we add the following in our try block in doInBackground :
Since we’ve returned this we ask the user for their 2FA password. Technically speaking that’s all we need to access their repos list, but if we want to do more than that we need to acquire an authorization token from GitHub. For this, we need to send a login request to the authorizations endpoint:
In order to request an authorization we must send a POST request in which we specify as JSON a title for the authorization. I found the easiest way to do this without using a try/catch block is by creating the JSON object from a HashMap. So we add this to the doInBackground method of the AsyncTask:
If the authentication is successful, the API will reply with a JSON containing a token field with our authentication token. I have made a method to extract it and save it to SharedPreferences for easy access:
Afterwards, we can login as we do with Basic Authentication, the only difference being that instead of sending a header that contains:
we send one that contains “token” instead of “Basic”, followed by the token of our authorization:
And since I’m saving the token as SharedPreferences, we can easily check if we have a token for a certain username by using contains :
And that’s it, we now have full access to the GitHub API! If you have any questions make sure to have a look at the full code on my GitHub page using the link at the top of the article or just leave a comment below!
Thanks for reading this article. You can connect with me on LinkedIn.
I’m currently looking for a job in the Geneva area , Switzerland, so please contact me if you know someone in need of a Mobile Developer with Java/Kotlin (Android) and JavaScript (React Native Android/iOS) experience.
If you liked this article, please hit the clap icon 👏 to show your support.
Источник
Android Studio не может войти в GitHub
У меня возникает эта проблема при входе в GitHub в Android Studio:
Не могу войти: не могу получить информацию о пользователе 404: не найден
Кто-нибудь сталкивался с этой проблемой? Как я могу это обойти?
16 ответов
Я использую «github.com» в качестве хоста (а не весь URL-адрес клона), а также мой логин и пароль на github, и могу войти в систему без каких-либо проблем.
Я тоже столкнулся с этой проблемой. Попробуйте использовать токен для входа в систему.
Авторизуйтесь на github.com в браузере. Зайдите в Настройки -> Настройки разработчика -> Личные токены доступа. Там вы можете создать новый токен, а затем вернуться в Android Studio и выбрать «Ввести токен» в приглашении для входа в систему.
Я работаю над 4.1.1 Android Studio, и это не позволило мне войти в систему с помощью логина + пароля.
Итак, мне удалось сгенерировать токен из Github (Учетная запись -> Настройки -> Персональные токены доступа -> Создать новый токен), но перед генерацией токена обязательно проверьте параметры «repo», «gist» и «read: org».
Оттуда все работает нормально.
На хосте вам нужно только указать «http://github.com»
Для меня проблема заключалась в том, что URL-адрес репозитория был установлен с помощью http:// , но учетные данные относятся к тому же URL-адресу, но с https:// . изменение URL-адреса репозитория на https:// решило мою проблему.
Вы можете использовать Token для входа в студию Android.
1. перейдите к своему github profile
2. нажмите settings
3. перейти к Developer settings
4. нажмите Personal access tokens
5. Generate new token
И скопируйте его и вставьте в окно выше в студии Android.
1- Перейдите на свою страницу github,
2- Откройте меню настроек и создайте новый токен
3- Скопируйте новый токен
4- Откройте Androdi studio goto VCS -> импортировать в систему управления версиями -> Поделиться проектом в Git Hub войти
5- Использовать параметр токена
6- Вставьте созданный и скопированный токен
7- Нажмите «Войти»
Не нужно менять URL
Я использую Android Studio 4.1
Я столкнулся с этой проблемой для моего частного репозитория, поэтому в Github я создал новый токен доступа и предоставил весь доступ для этого токена. Используйте этот токен в студии Android, это сработало для меня
Я справился с этой проблемой, используйте токен для входа в систему. таким образом создавать токены; просто контрольный список на
Используя «https://github.com/» и свои учетные данные, я получаю доступ
Из Android Studio.
- Перейти к настройкам
- Зайти на Github
- Убедитесь, что вы вошли в систему, используя созданный ключ токена аутентификации из Github.
- Перейти к настройкам
- Перейти в режим разработчика
- Сгенерируйте новый токен-ключ и дайте ему все права на доступ к аккаунту Github.
- Скопируйте новый сгенерированный ключ в токен доступа Android и нажмите OK, когда закончите.
Вы можете использовать токен для решения этой проблемы.
Войдите в учетную запись GitHub в браузере. Перейдите в НАСТРОЙКИ-> НАСТРОЙКИ РАЗРАБОТЧИКА-> ТОКЕНЫ ПЕРСОНАЛЬНОГО ДОСТУПА, здесь вы можете создать токен с подходящими областями действия. Помните, что выбор областей важен для доступа к токену в студии Android. После этого просто скопируйте сгенерированный токен и вставьте в студию Android.
Получайте удовольствие от программирования!
Из Android Studio.
Перейдите в настройки. Перейдите на Github. Убедитесь, что вы вошли в систему, используя созданный ключ токена аутентификации из Github.
С веб-сайта Github
Перейти к настройкам Зайдите в настройки разработчика Создать новый токен-ключ Дайте псевдоним ключу Token Отметьте repo, admin: org, gist . Нажмите кнопку «Создать токен». Скопируйте новый сгенерированный ключ в токен доступа Android и нажмите OK, когда закончите.
У меня такая же проблема как с Mac, так и с Windows. Создание токена личного доступа всегда решало для меня эту проблему. Войдите в github, нажмите на учетную запись> настройка> Настройки разработчиков> токены личного доступа
Создание токена, как описано, сработало для меня идеально. Необходимо предоставить такому токену правильные разрешения.
Я удалил все токены и создал новый со всем доступом, теперь он работает .
Источник
Creating a personal access token
In this article
You should create a personal access token to use in place of a password with the command line or with the API.
Note: If you use GitHub CLI to authenticate to GitHub on the command line, you can skip generating a personal access token and authenticate via the web browser instead. For more information about authenticating with GitHub CLI, see gh auth login .
Personal access tokens (PATs) are an alternative to using passwords for authentication to GitHub when using the GitHub API or the command line.
If you want to use a PAT to access resources owned by an organization that uses SAML SSO, you must authorize the PAT. For more information, see «About authentication with SAML single sign-on» and «Authorizing a personal access token for use with SAML single sign-on.»
As a security precaution, GitHub automatically removes personal access tokens that haven’t been used in a year. To provide additional security, we highly recommend adding an expiration to your personal access tokens.
A token with no assigned scopes can only access public information. To use your token to access repositories from the command line, select repo . For more information, see «Available scopes».
Creating a token
Verify your email address, if it hasn’t been verified yet.
In the upper-right corner of any page, click your profile photo, then click Settings.
In the left sidebar, click Developer settings.
In the left sidebar, click Personal access tokens.
Click Generate new token.
Give your token a descriptive name.
To give your token an expiration, select the Expiration drop-down menu, then click a default or use the calendar picker.
Select the scopes, or permissions, you’d like to grant this token. To use your token to access repositories from the command line, select repo.
Click Generate token.
Warning: Treat your tokens like passwords and keep them secret. When working with the API, use tokens as environment variables instead of hardcoding them into your programs.
To use your token to authenticate to an organization that uses SAML SSO, authorize the token for use with a SAML single-sign-on organization.
Using a token on the command line
Once you have a token, you can enter it instead of your password when performing Git operations over HTTPS.
For example, on the command line you would enter the following:
Personal access tokens can only be used for HTTPS Git operations. If your repository uses an SSH remote URL, you will need to switch the remote from SSH to HTTPS.
If you are not prompted for your username and password, your credentials may be cached on your computer. You can update your credentials in the Keychain to replace your old password with the token.
Instead of manually entering your PAT for every HTTPS Git operation, you can cache your PAT with a Git client. Git will temporarily store your credentials in memory until an expiry interval has passed. You can also store the token in a plain text file that Git can read before every request. For more information, see «Caching your GitHub credentials in Git.»
Источник
How to add GitHub Login button to your Android app using Kotlin
UPDATE [March 4rd, 2020]: AsyncTasks replaced with Coroutines
Today, I’ll show you how to implement the ‘Log in with GitHub’ button into your Android app.
We’re going to use 3-legged Authorization(OAuth) to get the authorization code and exchange it later for the access token. Using the access token, we’ll be able to get user’s information and email address making an HTTP request to https://api.github.com/user
Let’s get started!
First, we need to create the Client ID and Client Secret on the GitHub website.
Go to https://github.com/settings/developers and press the Register a new application button.
Fill the required fields and press Register application.
On the new page, you’ll see the Client ID and Client Secret we going to use later.
Adding the dependencies
In this tutorial, we’re going to use Coroutines, which will help us do HTTP POST requests easier.
In the build.gradle file of your app add the following dependency:
Creating the GitHub Login Button
First, add a Button to your XML file. In this example, we have a button in the middle of the activity_main.xml.
Create a new Kotlin object file by right-clicking on your app’s package name on the left side and go New > Kotlin File/Class.
Give it the name GithubConstants, choose Object and press OK.
Inside the new file, copy and paste the following code and replace the CLIENT_ID, CLIENT_SECRET and REDIRECT_URI with yours.
In your AndroidManifest.xml file, add internet permission.
In the Kotlin class of your Activity (In this example is the MainActivity), add a listener to your button, and create a Dialog with a WebView inside.
This WebView uses a custom WebViewClient, named GithubWebViewClient.
This helps to ‘catch’ the URL with the authorization code after the user has given access to your app.
After getting the authorization code, you need to exchange it for an access token by making an HTTP POST request to https://github.com/login/oauth/access_token
After having the access token, you can get user’s Id, Display Name, Profile pic URL and email address with an HTTP GET request.
If you have any questions, please feel free to leave a comment below
Источник