Я разрабатываю шаблон Cloudformation для создания пула пользователей Cognito, а затем настраиваю Grafana 6.0.2 с записями для использования этого пула для регистрации и входа в Oauth. Сейчас это отчасти работает, но у меня два плохих поведения (и, может быть, других, о которых я пока не знаю).
1) После создания новой учетной записи, даже в окне браузера Incognito, я получаю эту ошибку: «login.OAuthLogin (отсутствует сохраненное состояние)».
2) Если я вернусь на домашнюю страницу Grafana и выберу «Oauth login», я сразу войду в систему как новый пользователь, и у меня не будет возможности указать другое имя пользователя.
Я создал Cognito User Pool вручную, и это работало правильно. Я попытался воссоздать это в CloudFormation.
Python, оторванный от моего шаблона Cloudformation для настройки / создания Cognito User Pool & Client:
CreateUserPoolAndClientFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.6
Timeout: 60
Code:
ZipFile: |
import boto3
import cfnresponse
def handler(event, context):
responseData = {}
print (str(event))
try:
if event['RequestType'] == 'Create':
Environment = event['ResourceProperties']['Environment']
BaseUrl = event['ResourceProperties']['BaseUrl']
client = boto3.client('cognito-idp')
response = client.create_user_pool(
PoolName=Environment+'-userpool',
AutoVerifiedAttributes=['email'],
Schema=[
{
'Name': 'email',
'Required': True
}
]
)
CreatedUserPoolId = response['UserPool']['Id']
response = client.create_user_pool_client(
UserPoolId=CreatedUserPoolId,
GenerateSecret=True,
ClientName=Environment + '-client',
ReadAttributes=[
'address', 'birthdate', 'email', 'email_verified', 'family_name', 'gender', 'given_name', 'locale', 'middle_name', 'name', 'nickname', 'phone_number', 'phone_number_verified', 'picture', 'preferred_username', 'profile', 'updated_at', 'website', 'zoneinfo'
],
WriteAttributes=[
'address', 'birthdate', 'email', 'family_name', 'gender', 'given_name', 'locale', 'middle_name', 'name', 'nickname', 'phone_number', 'picture', 'preferred_username', 'profile', 'updated_at', 'website', 'zoneinfo'
],
SupportedIdentityProviders=['COGNITO'],
CallbackURLs=['https://' + BaseUrl + '','https://' + BaseUrl + '/login','https://' + BaseUrl + '/login/generic_oauth'],
LogoutURLs=['https://' + BaseUrl + '/login','https://' + BaseUrl + '/logout'],
AllowedOAuthFlows=['implicit','code'],
AllowedOAuthScopes=['email','openid','profile'],
AllowedOAuthFlowsUserPoolClient=True
)
CreatedClientId = response['UserPoolClient']['ClientId']
CreatedClientSecret = response['UserPoolClient']['ClientSecret']
response = client.create_user_pool_domain(
Domain = str(CreatedClientId),
UserPoolId = CreatedUserPoolId
)
responseData['UserPoolId'] = CreatedUserPoolId
responseData['ClientId'] = CreatedClientId
responseData['ClientSecret'] = CreatedClientSecret
print("SUCCESS, ResponseData=" + str(responseData))
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
else:
print("SUCCESS - operation not Create, ResponseData=" + str(responseData))
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID")
except Exception as e:
responseData['Error'] = str(e)
cfnresponse.send(event, context, cfnresponse.FAILED, responseData, "CustomResourcePhysicalID")
print("FAILED ERROR: " + responseData['Error'])
Общий раздел Oauth из моего файла Grafana ini:
[auth.generic_oauth]
enabled = true
name = OAuth
allow_sign_up = true
client_id = 6ghk6ekcdb7um021jcu5prdq6d
client_secret = 1090coldi5hba8ha9c52pq4f09hi2fm0mu5rqua7raaf9oqbq58
;scopes = user:email,read:org
scopes = openid profile email
auth_url = https://6ghk6ekcdb7um021jcu5prdq6d.auth.ap-southeast-2.amazoncognito.com/oauth2/authorize
token_url = https://6ghk6ekcdb7um021jcu5prdq6d.auth.ap-southeast-2.amazoncognito.com/oauth2/token
api_url = https://6ghk6ekcdb7um021jcu5prdq6d.auth.ap-southeast-2.amazoncognito.com/oauth2/userInfo
BaseUrl, переданный в шаблон Cloudformation, будет выглядеть как grafana.oursite.com и является доменом, управляемым AWS, предоставляющим HTTPS. 'Client_id', используемый в ini-файле Grafana, - это идентификатор пула пользователей Cognito, который Cognito использует для URL-адресов Oauth (AFAIK).
Спекуляция может быть полезной, но, пожалуйста, скажите, знаете ли вы или спекулируете - я делаю это для клиента и у меня крайний срок. Я не очень разбираюсь в этом, поэтому не стесняйтесь говорить больше, чем меньше.
Спасибо.