Thunderbird gmail oauth2 не работает

OAuth-авторизация в Mozilla Thunderbird: от зарождения до релиза

Некоторое время назад мы рассказывали о том, как в Mail.Ru реализован сбор почты с использованием протокола OAuth 2.0. Мы продолжаем повышать безопасность почты и продвигать стандарт OAuth 2.0 в массы. И сегодня расскажем о том, как мы добавили OAuth-авторизацию в почтовый клиент Mozilla Thunderbird. На этом примере мы разберем процесс внесения новой фичи в продукт с открытым исходным кодом, от создания тикета до релиза. Если вы давно хотели сделать свой первый pull request, но не знали как, — читайте нашу историю.

1. Общая схема работы

На действия пользователя Thunderbird открывает веб-вью с адресом для OAuth-авторизации. Если пользователь успешно прошел процедуру авторизации и согласился предоставить приложению доступ к своим данным, то мы перенаправляем пользователя на адрес, указанный в параметре redirect_uri . Так приложение получит авторизационный токен и сможет использовать его для работы с нашей почтовой службой. Адрес для запроса токена:

Стоит заметить, что значение localhost для параметра redirect_uri приложение задает самостоятельно, а параметр state (используется клиентом для поддержки связи между запросом и колбэком) не передает вовсе. Ниже представлена схема взаимодействия приложения с сервисом:

2. Как устроен процесс интеграции, основные этапы

Хотя сам процесс интеграции довольно простой и не занимает много времени, все же стоит рассказать об отдельных моментах, которые следует планировать заранее.

Поскольку Thunderbird — это продукт компании Mozilla, мы сразу отправились на MDN. Так мы быстро получили общее представление об основных этапах интеграции:

  1. Тикет на добавление почтового клиента.
  2. Тикет на добавление конфигурации в ISP-базу.
  3. Патч в репозиторий comm-central.
  4. Патч в ISP-базу.
  5. Тестовая сборка.
  6. Сохранение обратной совместимости.
  7. Тестирование функциональности в ранних релизах.
  8. Тестирование релиза.

Далее рассмотрим каждый этап в отдельности.

2.1. Тикет на добавление почтового клиента

Перед тем как ставить тикет, убедитесь, что до вас этого никто не сделал. Постановка тикета является ключевым этапом в решении любой похожей задачи, поэтому очень важно правильно заполнить все обязательные поля:

Продукт: Структура репозитория comm-central разделена на независимые продукты. С этим у нас проблем не возникло, поскольку название продукта MailNews сразу упоминается на стартовой странице.

Компонент: Напротив этого пункта есть подсказка, однако здесь и так интуитивно понятно, что работа связана с сетью, поэтому выбираем Networking.

Версия: Чтобы понять, какую версию релиза выбрать, следует обратиться к странице со списком релизов. Однако этой информации будет явно недостаточно, поскольку нам важно понимать, на каком этапе находится еще не вышедший релиз. С этим нам поможет календарь релизов. Более подробную информацию о релиз-цикле можно получить на соответствующей странице. Но если вы все-таки сомневаетесь, какую версию релиза выбрать, то не стесняйтесь задать свой вопрос в списке рассылок или IRC-канале. При крайней необходимости вам помогут ревьюверы тикета.

Платформа: В нашем случае продукт платформонезависимый ( all ).

Важность: Поскольку мы расширяем функциональность, тип будет enhancement .

  • Ключевые слова: Список ключевых слов ограничен. Беглый поиск по похожим тикетам подсказал выбрать feature , user-doc-needed .
  • Совет: чтобы случайно не пропустить какой-либо этап, добавьте к себе календарь.

    2.2. Тикет на добавление конфигурации в ISP-базу

    Нам попался хороший ревьювер, который помог с заполнением большинства полей и релизом. Смотрите пример нашего тикета.

    2.3. Патч в репозиторий comm-central

    Если вы обратили внимание, сообщество Mozilla очень трепетно относится к документированию своих продуктов. Руководство по сборке продукта, стилистике написания программного кода и пр. Все ссылки на это располагаются в одном месте и не требуют, как это часто бывает с другими продуктами, прохождения некоего квеста. Сразу скажу, что никакого «rocket science» в добавлении нового OAuth-провайдера в Thunderbird нет, — это становится понятно после грепа по репозиторию и беглого ознакомления с исходным кодом. Несмотря на то что файлов с ключевым словом OAuth было довольно много:

    Интуиция подсказывала, что все должно быть проще. И мы не ошиблись, когда открыли первый из списка файл:

    Не буду томить, просто смотрите дифф:

    Если вы обратили внимание, то, к сожалению, мы пока не поддержали новый протокол, который позволяет динамически регистрировать клиент, но мы над этим работаем! И далее аттач патча по номеру тикета:

    P. S. Будьте готовы к тому, что клонирование репозитория требует до 5 Гб свободного места на диске.

    2.4. Патч в ISP-базу

    Эта конфигурация необходима для выбора протокола, который будет использоваться по умолчанию. Пример файла-автоконфига: https://autoconfig.thunderbird.net/v1.1/mail.ru. SVN-репозиторий ISP находится по следующему адресу:

    Поскольку мы уже имели дело с этим конфигом ранее, то показать дифф будет проще, чем рассказать:

    На этом этапе торопиться не стоит, даже если ваш сервер уже поддерживает OAuth-авторизацию, ведь можно получить сайд-эффект в виде неработающей авторизации. В качестве альтернативы вы можете разместить файл автоконфига на своем сервере: https://autoconfig.mail.ru/mail/config-v1.1.xml. В таком случае у вашего файла будет более высокий приоритет и вы сможете самостоятельно управлять способом авторизации не только на этапе тестирования. Если у вашего почтового сервиса есть алиасы доменов, то переживать не стоит: ISP-сервер смотрит на MX-записи. Более подробно об этом способе конфигурации сервера смотрите здесь.

    Читайте также:  Chevrolet aveo не работает магнитола

    2.5. Тестовая сборка

    Добавляем конфигурацию для тестового окружения:

    Если во время сборки появится ошибка о том, что исходный код устарел, то выполните следующую команду и перезапустите сборку еще раз:

    Более подробно о сборке проекта смотрите здесь.

    Для OS X 10.9–10.10 (в 10.11 эта опция мешает сборке) может потребоваться добавить следующую опцию:

    Также в процессе сборки может возникнуть требование установить autoconf 2.13:

    Решение для OS X:

    Возможно, это наша вина, но по каким-то причинам файл configure сгенерировался с синтаксическими ошибками:

    Такая ошибка свидетельствует об отсутствии в системе компилятора YASM.

    Решение (для OS X):

    Информацию о возможных проблемах сборки можно посмотреть в файле client.mk. Будьте готовы к тому, что исходный код проекта и сборка будет занимать на диске 8,3 Гб!

    В конфигурации мы указали ключ —enable-debug , он поможет нам видеть всю отладочную информацию, включая исходящие запросы к сторонним сервисам.

    Команда run сама найдет путь к приложению и запустит его. В нашем случае после сборки приложение расположилось по следующему пути:

    Для автоматизации тестирования Thunderbird использует фреймворк MozMill и XPCShell. Запускаем модульные тесты:

    Более подробную информацию о модульном тестировании смотрите ниже по ссылкам:

    Запускаем интеграционные тесты:

    Для интеграционного тестирования используется фреймворк MozMill.

    После локального прогона тесты запускает ревьювер, он же и проверяет заявленную функциональность. Как только релиз-инженер включит ваш патч в релиз в Treeherder CI, будет запущен цикл регрессионного тестирования. Дополнительную информацию о других видах (например, тестирование на утечки памяти) тестирования смотрите по этой ссылке.

    Руководство по Treeherder CI смотрите здесь.

    2.6. Тестирование функциональности в ранних релизах

    Как только релиз-инженер включит ваш патч в ранний релиз, вы можете начинать следующий этап тестирования. Согласно рабочему процессу, первым собирается ранний релиз под названием Aurora, далее Beta и релиз. Ссылки на скачивание ранних релизов находятся здесь. Календарь поможет не пропустить важную для вас дату релиза.

    Общая схема этапов релиза выглядит так:

    Релиз-цикл каждого этапа занимает шесть недель.

    2.7. Сохранение обратной совместимости

    Для клиентов, которые еще не обновились до 45-го релиза, должна работать стандартная схема авторизации. И если об этом не подумать заранее, то пользователь всегда будет видеть ошибку авторизации (если вручную не сменит способ авторизации):

    Для того чтобы сохранить обратную совместимость, мы стали отдавать конфигурационный файл, ориентируясь на User-Agent:

    Теперь пользователи старых клиентов будут получать файл конфигурации без OAuth. Проверяем:

    2.8. Тестирование релиза

    Теперь, когда несколько долгих месяцев позади, релиз можно скачивать с главной страницы! Далее мы покажем, что же в итоге увидит пользователь.

    3. Сценарий использования

    Способов добавления почтового аккаунта в Thunderbird несколько, однако все они сводятся к одним и тем же действиям, поэтому рассмотрим самый очевидный:

    1. Открываем стартовую страницу. В разделе создания нового почтового аккаунта выбираем Email :

    2. Пропускаем этот шаг, поскольку у нас уже есть почтовый аккаунт:

    3. Добавляем почтовый адрес и жмем кнопку «Продолжить»:

    4. Выбираем протокол сбора почты ( IMAP ) и жмем кнопку «Готово»:

    5. На этом шаге проверяем настройки почтового сервера и, если все в порядке, жмем кнопку «Готово»:

    6. Вводим авторизационные данные от своей учетной записи в Mail.Ru:

    7. Соглашаемся с тем, что Thunderbird будет собирать почту с нашего аккаунта:

    8. Ожидаем, когда письма будут скачаны:

    4. Заключение

    Как видите, мы стараемся развивать не только свои opensource-проекты, но и сторонние. Мы крайне щепетильны в вопросах безопасности, поэтому решили подключиться к разработке Mozilla Thunderbird и помочь с реализацией OAuth 2.0. Надеемся, наш пост воодушевит кого-то сделать свой первый pull request, и мир opensource статет чуточку лучше.

    Источник

    Thunderbird gmail oauth2 не работает

    Поиск в Поддержке

    1. Начало
    2. Форумы поддержки
    3. Thunderbird
    4. Enabling OAuth2 on existing GMail.

    Избегайте мошенников, выдающих себя за службу поддержки. Мы никогда не попросим вас позвонить, отправить текстовое сообщение или поделиться личной информацией. Сообщайте о подозрительной активности, используя функцию «Пожаловаться».

    Learn More

    Enabling OAuth2 on existing GMail account (bug 1176773)

    • 4 ответа
    • 10 имеют эту проблему
    • 85 просмотров
    • Последний ответ от LordCrc

    I’ve just upgraded to Thunderbird 38.0.1 from version 37.something, and I cannot seem to get OAuth2 to work with my existing GMail account.

    My settings were as follows: Username: my.account@gmail.com Server: imap.google.com Port: 993 Security: SSL/TLS Authentication: Normal password

    This worked and still works fine. However if I then change Autentication to OAuth2, save and restart Thunderbird, I get the following error message when trying to view my gmail folder: «The IMAP server my.account@gmail.com does not support the selected authentication method».

    I’ve tried googling but I can’t seem to find any word on how to configure OAuth2 with GMail beyond switching it on. So any ideas on how to get this working?

    Изменено 23 июня 2015 г., 02:13:53 -0700 Wayne Mery

    Источник

    Thunderbird gmail oauth2 не работает

    My old Gmail account works in Thunderbird 68.12.1 (32-bit) with no problems, that is, it sends and receives mail. Now I decided to add another Gmail account to Thunderbird. It receives mail without problems, but it can’t send mail. If that matters, I have total 4 accounts in Thunderbird (the other 2 aren’t Gmail accounts and they’re working).

    Читайте также:  Холодильник беко не работает морозилка

    Both accounts have identical settings:

    1) both are Gmail mails, that is, mail address is like name1.name2@gmail.com and those mails aren’t new (I’ve had them for several years, but in Thunderderbird was using just one of them).

    2) the option for «Less secure app access allowed» is turned ON in Gmail account security

    3) POP mail server settings: Server Name: pop.gmail.com Port: 995 Connection security: SSL/TLS Authentication method: Normal password

    4) SMTP server settings in Thunderbird: Server Name: smtp.gmail.com Port: 465 Connection security: SSL/TLS Authentication method: OAuth2

    So why my new account can’t send mails with Authentication method: OAuth2 (it can only send mails using Authentication method: Normal password).

    Isn’t that the opposite of what should be happening? I thought that Gmail was supposed require OAuth2 method. Anyway, what I’m missing to make those accounts identical for Gmail?

    Выбранное решение

    The attached picture shows the cookies settings in TB Options/Privacy. Make sure ‘Accept cookies from sites’ is checked for OAuth2 to work.

    Все ответы (16)

    What prevents you from sending messages? Is there any error message? Please be more specific.

    Change the authentication on the incoming POP server to OAuth2, to match the outgoing. In Tools/Account Settings, select each gmail account in the left pane, then make sure each Outgoing Server (SMTP) has the same User Name as the selected account (Edit SMTP server. to check). Remove all passwords and oauth tokens from Options/Security/Passwords/Saved Passwords, restart TB, enter the account password in the OAuth browser window.

    What prevents you from sending messages? Is there any error message? Please be more specific.

    When I try to send message on my second Gmail account from Thunderbird using OAuth2 I’m getting this window «One account. All of Google.» (see the picture below), but if I enter my e-mail there and press Next nothing happens, it opens the same window where I have to enter e-mail again and it doesn’t ask to enter password (I can join that Google account from any browser, but not from this window, which pops up from Thunderbird). I don’t get any of this bug on my first Gmail account in Thunderbird.

    What prevents you from sending messages? Is there any error message? Please be more specific.

    When nothing happens after clicking Next, it’s usually because cookies aren’t allowed in TB Options/Privacy; they are needed for OAuth2.

    Change the authentication on the incoming POP server to OAuth2, to match the outgoing. In Tools/Account Settings, select each gmail account in the left pane, then make sure each Outgoing Server (SMTP) has the same User Name as the selected account (Edit SMTP server. to check). Remove all passwords and oauth tokens from Options/Security/Passwords/Saved Passwords, restart TB, enter the account password in the OAuth browser window.

    Did all these steps, still the same result (now I also can’t receive mails when OAuth2 is set for POP, the same window pops up).

    When nothing happens after clicking Next, it’s usually because cookies aren’t allowed in TB Options/Privacy; they are needed for OAuth2.

    I’m using Google Chrome and all cookies are allowed (look at image below).

    I think it’s a problem with Thunderbird. Have to tried to add a new Gmail account to Thunderbird? Can you confirm that OAuth2 is working for POP and SMTP on that new account?

    Change the authentication on the incoming POP server to OAuth2, to match the outgoing. In Tools/Account Settings, select each gmail account in the left pane, then make sure each Outgoing Server (SMTP) has the same User Name as the selected account (Edit SMTP server. to check). Remove all passwords and oauth tokens from Options/Security/Passwords/Saved Passwords, restart TB, enter the account password in the OAuth browser window.

    When nothing happens after clicking Next, it’s usually because cookies aren’t allowed in TB Options/Privacy; they are needed for OAuth2.

    Chrome or any other browser’s cookies are not relevant. The relevant ones are in TB Options/Privacy. Allow all cookies or at least for *.google.com.

    Chrome or any other browser’s cookies are not relevant. The relevant ones are in TB Options/Privacy. Allow all cookies or at least for *.google.com.

    My default browser is Chrome. If Firefox cookie settings matter for Thunderbird then does it mean that Thunderbird can’t be securely used without installed Firefox? Anyway, here is my cookie settings in Firefox:

    Chrome or any other browser’s cookies are not relevant. The relevant ones are in »’TB»’ Options/Privacy. Allow all cookies or at least for *.google.com.

    Выбранное решение

    The attached picture shows the cookies settings in TB Options/Privacy. Make sure ‘Accept cookies from sites’ is checked for OAuth2 to work.

    The attached picture shows the cookies settings in TB Options/Privacy. Make sure ‘Accept cookies from sites’ is checked for OAuth2 to work.

    Thank you very much, now it’s working as expected! Somehow I’ve misunderstood what you’ve already clearly explained in previous post 🙂 (now it all makes sense)

    Читайте также:  Вообще не работают usb

    A small mystery: why my first account was working without these cookies?

    The attached picture shows the cookies settings in TB Options/Privacy. Make sure ‘Accept cookies from sites’ is checked for OAuth2 to work.

    Cookies are not required for normal password authentication.

    Hello, I have this problem now, too, I followed all of the steps including allowing cookies (all settings were already entered the way they should be according to this thread but it is still not sending any emails from my yahoo account using firefox). I have no idea what I should do — I have restarted about 100 times now.

    Hello, I have this problem now, too, I followed all of the steps including allowing cookies (all settings were already entered the way they should be according to this thread but it is still not sending any emails from my yahoo account using firefox). I have no idea what I should do — I have restarted about 100 times now.

    Check that OAuth2 is also the authentication method for the outgoing server.

    Hello, I have this problem now, too, I followed all of the steps including allowing cookies (all settings were already entered the way they should be according to this thread but it is still not sending any emails from my yahoo account using firefox). I have no idea what I should do — I have restarted about 100 times now.

    Hi, actually that was the problem. As mentioned, I had all the right settings and also OAuth2 on the outgoing server but I thought that maybe considering this is yahoo business mail we’re dealing with and knowing how awful they are, they may have it upside down. And they do. The trick was to set the outgoing to «normal password». It has since worked fine and has not asked me to enter passwords again. Thanks for responding though!

    I have this problem as well — often (say one in three attempts) to either read IMAP or send SMTP is rejected due to «authentication error».

    Cookies are (and were before) allowed in TB -> privacy, and OAuth2 is the authentication method for IMAP and SMTP.

    Something is definitely broken in TB.

    (I read and write to the same GMAIL servers on my ANDROID devices using a3rd party app (AQUAMAIL), and there is never any authentication problem there.)

    Изменено 3 ноября 2020 г., 04:14:09 -0800 AY

    I have this problem as well — often (say one in three attempts) to either read IMAP or send SMTP is rejected due to «authentication error». Cookies are (and were before) allowed in TB -> privacy, and OAuth2 is the authentication method for IMAP and SMTP. Something is definitely broken in TB. (I read and write to the same GMAIL servers on my ANDROID devices using a3rd party app (AQUAMAIL), and there is never any authentication problem there.)

    There are millions of TB users with working gmail accounts, so I highly doubt TB is broken. If you’ve followed all the instructions and it’s not working, there is probably some other program (antivirus, VPN) interfering with the connection. Start your computer in safe mode and then run TB, and see if it works.

    I have this problem as well — often (say one in three attempts) to either read IMAP or send SMTP is rejected due to «authentication error». Cookies are (and were before) allowed in TB -> privacy, and OAuth2 is the authentication method for IMAP and SMTP. »’Something is definitely broken in TB. »’ (I read and write to the same GMAIL servers on my ANDROID devices using a3rd party app (AQUAMAIL), and there is never any authentication problem there.)

    Mine is broken as well. Same issue, gmail accounts broken right after update. OATH2 is correctly selected, cookies enabled as per the guidance here (both were already the case) and I’m constantly getting this message, so something is wrong. I checked all of the settings mentioned 3 times. It’s complaining about the incoming imap settings which again have been checked 3 times. So time for me to move away from TB unfortunately, since I have several gmail accounts affected by this. I have also checked the google documentation, all is as it should be. Next I’ll be removing and re-adding an account (letting TB grab the settings automatically).

    Edit: Yep, when re-adding the account, I had to reconnect thunderbird to gmail as an «allowed app» again, so the previous «allowed» connection to Thunderbird was somehow insufficient or wiped out. So now I have to remove, re-auth, and re-add all my accounts, which is a pain in the butt with 2 factor auth set on all of them. If this happens again, thunderbird is going in the bin.

    Изменено 15 ноября 2020 г., 14:33:04 -0800 SomeGirl

    Источник

    Оцените статью