Mule 3.5 - пример Google OAuth2
Я пытаюсь подключить Mule 3.5 к Google API (задачи, календарь и т. Д.), Но у меня возникают всевозможные проблемы с аутентификацией OAuth2.
Может кто-нибудь дать мне пример XML-файла проекта Mule с работающим Примером Google OAuth2 (и, возможно, настройками в консоли API Google), пожалуйста.
Ссылка тоже подойдет.
3 ответа
Google Connectors Suite для Mule содержит полный пример, включая конфигурацию Mule XML.
Вам необходимо создать приложение в своей учетной записи Google Developer ( https://console.developers.google.com/) с помощью кнопки "Создать проект". Запомните свой идентификатор проекта, он вам понадобится в конфигурации коннектора Google.
Затем вам нужно нажать на приложение и перейти к APIs и Auth. Убедитесь, что для нужного вам API установлено состояние "ON". В этом случае вы, вероятно, захотите включить Календарь и все остальное, что вам не нужно. Имейте в виду, что значительное количество вызовов в службу календаря может повлечь за собой расходы или ограничения квоты.
Также в разделе APIs & Auth на левой стороне консоли разработчика Google вам необходимо выбрать учетные данные. Затем нажмите красную кнопку Создать новый идентификатор клиента. Это даст вам две важные части информации:
- Идентификатор клиента - это указывается в вашем ключе потребителя в соединителе Google в Mule
- Секрет клиента - это входит в ваш 'customerSecret' в соединителе Mule
Другая важная вещь для настройки - URI перенаправления. Это должно быть что-то вроде:
http://localhost:8081/oauth2callback
Это должно соответствовать тому, что вы положили в вашу конфигурацию разъема. Если вы используете свой сервер Mule за брандмауэром, вам необходимо настроить такие вещи, как прокси-сервер, чтобы этот обратный вызов мог достичь вашего сервера.
Вот грубый пример того, что мне удалось получить работу. Обязательно замените clientID clientSecret и имя приложения соответствующим образом.
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:json="http://www.mulesoft.org/schema/mule/json"
xmlns:https="http://www.mulesoft.org/schema/mule/https"
xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
xmlns:objectstore="http://www.mulesoft.org/schema/mule/objectstore"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns:google-calendars="http://www.mulesoft.org/schema/mule/google-calendars"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/google-calendars
http://www.mulesoft.org/schema/mule/google-calendars/1.0/mule-google-calendars.xsd
http://www.mulesoft.org/schema/mule/objectstore
http://www.mulesoft.org/schema/mule/objectstore/1.0/mule-objectstore.xsd
http://www.mulesoft.org/schema/mule/ee/tracking
http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/https
http://www.mulesoft.org/schema/mule/https/current/mule-https.xsd
http://www.mulesoft.org/schema/mule/json
http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
<!-- The 'consumerKey' is Client ID of you google application
The 'consumerSecret' is the Client Secret of the google application
The 'applicationName' is the application name you supplied (or Google created for you) when you created your application
on the google developer console
-->
<google-calendars:config-with-oauth
name="Google_Calendars"
consumerKey="replace-with-client-ID"
consumerSecret="replace-with-client-secret" doc:name="Google Calendars"
applicationName="replace-with-application-name">
<!-- The values here need to match the redirect URL you authorized for your Google Application
In this case the callback URL would be http://localhost:8081/ouath2callback
-->
<google-calendars:oauth-callback-config
domain="localhost" localPort="8081" path="oauth2callback" remotePort="8081" />
</google-calendars:config-with-oauth>
<!-- This is the objectstore that stores your Auth key which is used in the second flow -->
<objectstore:config name="ObjectStore" doc:name="ObjectStore" />
<!-- The first flow is executed when you go to http://localhost:8080/oauth-authorize
It initiates the Google authentication and if successful gets the auth key and puts it into the object store -->
<flow name="authorizationAndAuthenticationFlow" doc:name="authorizationAndAuthenticationFlow">
<http:inbound-endpoint exchange-pattern="request-response"
host="localhost" port="8080" path="oauth-authorize" doc:name="HTTP" />
<google-calendars:authorize config-ref="Google_Calendars"
doc:name="Google Calendars" />
<!-- Your Auth token is store in the key 'accessTokenId' -->
<objectstore:store config-ref="ObjectStore" key="accessTokenId"
value-ref="#[flowVars['OAuthAccessTokenId']]" overwrite="true"
doc:name="ObjectStore" />
</flow>
<!-- This flow can be called after the authentication is complete. It uses the previously stored token and to retreive your
Calendars and return them as JSON -->
<flow name="getInformationFromCalendar" doc:name="getInformationFromCalendar">
<http:inbound-endpoint exchange-pattern="request-response"
host="localhost" port="8081" doc:name="HTTP" />
<!-- The enricher adds the access token to your message -->
<enricher target="#[flowVars['accessTokenId']]" doc:name="Message Enricher">
<objectstore:retrieve config-ref="ObjectStore"
key="accessTokenId" defaultValue-ref="#['']" doc:name="Get AccessToken" />
</enricher>
<expression-filter expression="#[flowVars['accessTokenId'] != '']"
doc:name="Is Access Token Set" />
<!-- gets your first 200 calendars using the accessToken that you enriched the message with-->
<google-calendars:get-calendar-list
config-ref="Google_Calendars" maxResults="200"
pageToken="#[flowVars['GoogleCalendar_NEXT_PAGE_TOKEN']]" doc:name="Google Calendars"
accessTokenId="#[flowVars['accessTokenId']]" />
<json:object-to-json-transformer
doc:name="Object to JSON" />
</flow>
</mule>
С тех пор мы опубликовали документацию по использованию соединителей OAuth. Дайте нам знать, если это полезно.