简体   繁体   中英

How to store and access microsoft office365 account token inside AWS Lambda in python3.6

I have zipped and uploaded a python library O365 for accessing MS outlook calendar inside AWS Lambda-Layer. I'm able to import it, but the problem is the authorization. When I tested it in local the bearer token was generated and stored in the local txt file using the FileSytemTokenBackend .

But When I load this into AWS Lambda using layers, it is again asking to copy paste the URL process which is not able to fetch from the layer token file. And I have tried FireSystemTokenBackend , but that also I'm failed to configure successfully. I have used this Token storage docs in local while testing the functionality.

My question is how to store and authenticate my account using the token file generated in my local. Because in the AWS lambda the input() functionality is throwing error in runtime. How can I keep that token file inside the aws lambda and use it without doing authentication everytime?

I have faced the same issue. The lambda filesystem is temporal, so you will need to do the autenticate process every time you run the function and the o365 lib will ask for the url. So try saving your token (o365_token.txt) in S3 instead of getting it in lambda filesystem and the use this token for authentication. I hope this code will help you:

import boto3
bucket_name = 'bucket_name' 

# replace with your bucket name
filename_token = 'o365_token.txt' 

# replace with your AWS credentials
s3 = boto3.resource('s3',aws_access_key_id='xxxx', aws_secret_access_key='xxxx') 

# Read the token in S3 and save to /tmp directory in Lambda 
s3.Bucket(bucket_name).download_file(filename_token, f'/tmp/{filename_token}') 

# Read the token in /tmp directory
token_backend = FileSystemTokenBackend(token_path='/tmp', 
token_filename=filename_token)

# Your azure credentials
credentials = ('xxxx', 'xxxx')
account = Account(credentials,token_backend=token_backend)

# Then do the normal authentication process and include the refresh token command
if not account.is_authenticated:
    account.authenticate()
account.connection.refresh_token()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM