Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7bb2ba6

Browse files
committed
Merge branch 'batch3' of https://github.com/oracle/oracle-functions-samples into batch3
2 parents 057e831 + 8f29522 commit 7bb2ba6

File tree

10 files changed

+185
-0
lines changed

10 files changed

+185
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.DS_Store
2+
__pycache__
3+
test.py
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# Function that validates an API key
2+
This is a sample function that can be used for a simple "API-Key" validation. An API-Key is a simple method for securing an API by requiring the client to pass a specific token. The gateway can use this as a custom authorizer to validate requests and only allow clients who pass the API-Key.
3+
4+
As you make your way through this tutorial, look out for this icon ![user input icon](./images/userinput.png).
5+
Whenever you see it, it's time for you to perform an action.
6+
7+
8+
## Prerequisites
9+
Before you deploy this sample function, make sure you have run step A, B and C of the [Oracle Functions Quick Start Guide for Cloud Shell](https://www.oracle.com/webfolder/technetwork/tutorials/infographics/oci_functions_cloudshell_quickview/functions_quickview_top/functions_quickview/index.html)
10+
* A - Set up your tenancy
11+
* B - Create application
12+
* C - Set up your Cloud Shell dev environment
13+
* D - Choose an back-end you would like to protect. This can be any back-end you already have access to, or you can use the [Display HTTP Request sample](../oci-apigw-display-httprequest-info-python)
14+
15+
16+
## List Applications
17+
Assuming your have successfully completed the prerequisites, you should see your
18+
application in the list of applications.
19+
```
20+
fn ls apps
21+
```
22+
23+
24+
## Review and customize the function
25+
Review the following files in the current folder:
26+
* the code of the function, [func.py](./func.py)
27+
* its dependencies, [requirements.txt](./requirements.txt)
28+
* the function metadata, [func.yaml](./func.yaml)
29+
30+
31+
## Deploy the function
32+
In Cloud Shell, run the *fn deploy* command to build the function and its dependencies as a Docker image,
33+
push the image to OCIR, and deploy the function to Oracle Functions in your application.
34+
35+
![user input icon](./images/userinput.png)
36+
```
37+
fn -v deploy --app <app-name>
38+
```
39+
40+
41+
## Set the function configuration values
42+
The function requires the following configuration values to be set:
43+
- FN_API_KEY
44+
45+
![user input icon](../images/userinput.png)
46+
47+
Use the *fn CLI* to set the config value:
48+
```
49+
fn config function <app-name> <function-name> FN_API_KEY <API key value>
50+
```
51+
e.g.
52+
```
53+
fn config function myapp oci-apigw-apikey-validation-python FN_API_KEY XXXXXXXXXXXX
54+
```
55+
Remember what you chose as you will need it later
56+
57+
## Create the API Gateway
58+
The functions is meant to be invoked through API Gateway.
59+
60+
![user input icon](./images/userinput.png)
61+
62+
On the OCI console, navigate to *Developer Services* > *API Gateway*. Click on `Create Gateway`. Provide a name, set the type to "Public", select a compartment, a VCN, a public subnet, and click `Create`.
63+
64+
![APIGW create](./images/apigw-create.png)
65+
66+
Once created, click on your gateway. Under *Resources*, select *Deployments* and click `Create Deployment`.
67+
68+
* Provide a name, a path prefix ("/fn-samples/v1/python" for example).
69+
* Add Authentication
70+
* Authentication Type: *Custom*
71+
* Choose the application and function you created for your API-Key validation function
72+
* Choose your Authentication token, you can use either Header or Query Parameter
73+
* Give a name to the token
74+
75+
Click *Save Changes* when you are finished
76+
![APIGW deployment create](./images/apigw-deployment-create.png)
77+
78+
click `Next`. Provide a name to the route ("/http-info" for example), select methods "GET" and "POST", select your back-end of choice such as if you have the .
79+
80+
![APIGW deployment create](./images/apigw-deployment-create-2.png)
81+
82+
Click `Next` and finally, click `Save Changes`.
83+
84+
Note the endpoint of your API Gateway deployment.
85+
86+
![APIGW deployment endpoint](./images/apigw-deployment-endpoint.png)
87+
88+
89+
## Create or Update your Dynamic Group for API Gateway
90+
In order to invoke functions, your API Gateway must be part of a dynamic group.
91+
92+
When specifying the *Matching Rules*, we suggest matching all functions in a compartment with:
93+
```
94+
ALL {resource.type = 'ApiGateway', resource.compartment.id = 'ocid1.compartment.oc1..aaaaaxxxxx'}
95+
```
96+
97+
98+
## Create or Update IAM Policies for API Gateway
99+
Create a new policy that allows the API Gateway dynamic group to invoke functions. We will grant `use` access to `functions-family` in the compartment.
100+
101+
![user input icon](./images/userinput.png)
102+
103+
Your policy should look something like this:
104+
```
105+
Allow dynamic-group <dynamic-group-name> to use functions-family in compartment <compartment-name>
106+
```
107+
108+
For more information on how to create policies, check the [documentation](https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policysyntax.htm).
109+
110+
111+
## Invoke the function
112+
The function returns the information of the HTTP request through API Gateway.
113+
114+
![user input icon](./images/userinput.png)
115+
116+
Set the Environment variable "APIGW_ENDPOINT" to the value of the endpoint of your API Gateway deployment, e.g.
117+
```
118+
export APIGW_ENDPOINT=https://xxxxx.apigateway.us-phoenix-1.oci.customer-oci.com/v1
119+
```
120+
121+
Use the curl command to make the HTTP request and specify the API Key in your request:
122+
```
123+
curl -v -H "x-api-key:<value from FN_API_KEY>" $APIGW_ENDPOINT/http-info
124+
```
125+
You should receive the information from the HTTP request (or whatever back-end you chose)
126+
127+
Try sending a request with a non-matching key, or no key at all.
128+
129+
The gateway will reject the request with an HTTP401
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#
2+
# oci-apigw-apikey-validation-python version 1.0.
3+
#
4+
# Copyright (c) 2020 Oracle, Inc.
5+
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
6+
#
7+
8+
import io
9+
import json
10+
import logging
11+
import datetime
12+
13+
from datetime import timedelta
14+
15+
from fdk import response
16+
17+
18+
def handler(ctx, data: io.BytesIO=None):
19+
auth_token = "invalid"
20+
token = "invalid"
21+
apiKey = "invalid"
22+
expiresAt = (datetime.datetime.utcnow() + timedelta(seconds=60)).replace(tzinfo=datetime.timezone.utc).astimezone().replace(microsecond=0).isoformat()
23+
24+
try:
25+
auth_token = json.loads(data.getvalue())
26+
token = auth_token.get("token")
27+
28+
app_context = dict(ctx.Config())
29+
apiKey = app_context['FN_API_KEY']
30+
31+
if token == apiKey:
32+
return response.Response(
33+
ctx,
34+
status_code=200,
35+
response_data=json.dumps({"active": True, "principal": "foo", "scope": "bar", "clientId": "1234", "expiresAt": expiresAt, "context": {"username": "wally"}})
36+
)
37+
38+
except (Exception, ValueError) as ex:
39+
logging.getLogger().info('error parsing json payload: ' + str(ex))
40+
pass
41+
42+
return response.Response(
43+
ctx,
44+
status_code=401,
45+
response_data=json.dumps({"active": False, "wwwAuthenticate": "API-key"})
46+
)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
schema_version: 20180708
2+
name: oci-apigw-apikey-validation-python
3+
version: 0.0.3
4+
runtime: python
5+
entrypoint: /python/bin/fdk /function/func.py handler
6+
memory: 256
135 KB
Loading[フレーム]
109 KB
Loading[フレーム]
118 KB
Loading[フレーム]
27.6 KB
Loading[フレーム]
2.96 KB
Loading[フレーム]
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
fdk

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /