storj.io/minio@v0.0.0-20230509071714-0cbc90f649b1/docs/sts/web-identity.py (about)

     1  #!/usr/bin/env python
     2  # -*- coding: utf-8 -*-
     3  # Licensed under the Apache License, Version 2.0 (the "License");
     4  # you may not use this file except in compliance with the License.
     5  # You may obtain a copy of the License at
     6  #
     7  #     http://www.apache.org/licenses/LICENSE-2.0
     8  #
     9  # Unless required by applicable law or agreed to in writing, software
    10  # distributed under the License is distributed on an "AS IS" BASIS,
    11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  # See the License for the specific language governing permissions and
    13  # limitations under the License.
    14  
    15  import json
    16  import logging
    17  import urllib
    18  from uuid import uuid4
    19  
    20  import boto3
    21  import requests
    22  from botocore.client import Config
    23  from flask import Flask, request
    24  
    25  boto3.set_stream_logger('boto3.resources', logging.DEBUG)
    26  
    27  authorize_url = "http://localhost:8080/auth/realms/minio/protocol/openid-connect/auth"
    28  token_url = "http://localhost:8080/auth/realms/minio/protocol/openid-connect/token"
    29  
    30  # callback url specified when the application was defined
    31  callback_uri = "http://localhost:8000/oauth2/callback"
    32  
    33  # keycloak id and secret
    34  client_id = 'account'
    35  client_secret = 'daaa3008-80f0-40f7-80d7-e15167531ff0'
    36  
    37  sts_client = boto3.client(
    38      'sts',
    39      region_name='us-east-1',
    40      use_ssl=False,
    41      endpoint_url='http://localhost:9000',
    42  )
    43  
    44  app = Flask(__name__)
    45  
    46  
    47  @app.route('/')
    48  def homepage():
    49      text = '<a href="%s">Authenticate with keycloak</a>'
    50      return text % make_authorization_url()
    51  
    52  
    53  def make_authorization_url():
    54      # Generate a random string for the state parameter
    55      # Save it for use later to prevent xsrf attacks
    56  
    57      state = str(uuid4())
    58      params = {"client_id": client_id,
    59                "response_type": "code",
    60                "state": state,
    61                "redirect_uri": callback_uri,
    62                "scope": "openid"}
    63  
    64      url = authorize_url + "?" + urllib.parse.urlencode(params)
    65      return url
    66  
    67  
    68  @app.route('/oauth2/callback')
    69  def callback():
    70      error = request.args.get('error', '')
    71      if error:
    72          return "Error: " + error
    73  
    74      authorization_code = request.args.get('code')
    75  
    76      data = {'grant_type': 'authorization_code',
    77              'code': authorization_code, 'redirect_uri': callback_uri}
    78      access_token_response = requests.post(
    79          token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
    80  
    81      print('body: ' + access_token_response.text)
    82  
    83      # we can now use the access_token as much as we want to access protected resources.
    84      tokens = json.loads(access_token_response.text)
    85      access_token = tokens['access_token']
    86  
    87      response = sts_client.assume_role_with_web_identity(
    88          RoleArn='arn:aws:iam::123456789012:user/svc-internal-api',
    89          RoleSessionName='test',
    90          WebIdentityToken=access_token,
    91          DurationSeconds=3600
    92      )
    93  
    94      s3_resource = boto3.resource('s3',
    95                                   endpoint_url='http://localhost:9000',
    96                                   aws_access_key_id=response['Credentials']['AccessKeyId'],
    97                                   aws_secret_access_key=response['Credentials']['SecretAccessKey'],
    98                                   aws_session_token=response['Credentials']['SessionToken'],
    99                                   config=Config(signature_version='s3v4'),
   100                                   region_name='us-east-1')
   101  
   102      bucket = s3_resource.Bucket('testbucket')
   103  
   104      for obj in bucket.objects.all():
   105          print(obj)
   106  
   107      return "success"
   108  
   109  
   110  if __name__ == '__main__':
   111      app.run(debug=True, port=8000)