cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How to use XSUAA in FastAPI Python app

Mohan-Sharma
Product and Topic Expert
Product and Topic Expert
0 Likes
1,975

Hi there, 

I have a fastapi app with 2 routes, one for rendering an html page and one for serving a request. I am using Jinja2 for templating.

Example of one of the route:

@router.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

My manifest.yaml for deploying it to cloud foundry:

---
applications:
- name: fastapi-app
  disk_quota: 2048M
  memory: 256M
  path: ./
  routes:
    -   route: fastapi-app.cfapps.eu10.hana.ondemand.com
  buildpacks:
  - python_buildpack
  command: uvicorn com.crack.snap.make.app:app --host 0.0.0.0 --port $PORT
  services:
    - app-xsuaa
    - app-logging-service
  logging:
    level: error
  env:
    PYTHONUNBUFFERED: true
    xsuaa_connectivity_instance_name: "app-xsuaa"
    xsuaa_destination_instance_name: "app-xsuaa"

How do I protect these fastapi routes directly using XSUAA, without having to create one more webapp then use app-router and then forwarding the request to fastapi app?

Also I want the fastapi to use the sub-account's default authentication which we do by using redirect-url of xs-security.json

{
	"xsappname": "fastapi-app",
	"tenant-mode": "dedicated",
	"scopes": [{
		"name": "$XSAPPNAME.fastapi_scope"
	}],
	"role-templates": [{
		"name": "FastAPIRoleTemplate",
		"default-role-name": "FastAPIRole",
		"description": "Role template for app users",
		"scope-references": ["$XSAPPNAME.fastapi_scope"]
	}
	],
	"oauth2-configuration": {
		"redirect-uris": [
			"https://*.cfapps.eu10.hana.ondemand.com/**"
		]
	}
}

Any help on achieving this will be really appreciated, we can also have a blog post on the same topic

SAP BTP, Cloud Foundry runtime and environment Python SAP BTP Security 

View Entire Topic
gregorw
SAP Mentor
SAP Mentor
0 Likes

The tutorial Create an Application with Cloud Foundry Python Buildpack provides an example using Flask. Maybe you can adopt that to FastAPI. Would be great if you share it afterwards.

Mohan-Sharma
Product and Topic Expert
Product and Topic Expert
0 Likes
@gregorw, thank you for the prompt help.. But the problem with the approach defined above is we need to create a separate webapp for user landing, then forward the user to the actual fastapi app. The fastapi alone is capable to having the frontend templates, then do we really need to have a separate node app(app router) just for landing the user?
gregorw
SAP Mentor
SAP Mentor
Using the Approuter is the best practice. It implements the user authentication flow for you and you can use destinations to call the backend.