RESTful and HTTP APIs in Pyramid Transcripts
Chapter: Authenticated services
Lecture: Authorization concepts
0:01 Let's review what we had to do to add authorization to our service. First of all, we have to have users who are going to authorize
0:08 so we added a user type by creating class user deriving from sqlalchemy base, setting the table name, creating the columns,
0:16 the id we don't really do anything with so autoincrementing id that seemed totally fine, obviously having idea when these users were created is handy
0:25 so we added a create a datetime column and we added now as the function to be called during inserts,
0:32 so that we don't have to think about it just magically the created time gets set;
0:35 then we have their name, in the code we actually added a hashed password because you got to have some way for them to log in,
0:42 but it didn't really matter for the example we used, so we have their name which has to be indexable and unique,
0:47 and we gave him an api key which is also unique and indexable. And we just used the uuid function to generate
0:55 a nice long random global unique identifier type of thing, so you can use whatever you want there, but I think that's a pretty solid bet.
1:03 Remember we also had to import this somewhere before that table would get created,
1:09 now in reality, it really kind of depends on how you interact with this code whether or not that's required, but it's a good practice
1:14 to just explicitly import all of those sqlalchemy types, where you're calling create all on the sqlalchemy base.
1:21 So we said let's pass this api key in the authorization header in the slides you have this function parse api key from header
1:28 and it just grans that and returns a value or none if it's not there so if there's no api key, we're going to return missing api key
1:35 then we're going to go try to find the user with that api key and we'll say if there's no user, sorry there's invalid api key
1:42 really like there's no user found corresponding to this api key, it was validly formed but there's no user, and if that worked
1:50 we have the user back then we set the request.api_user so if we need to work with them later, we can,
1:55 and we just delegate the call we just pass the call along to that API function called func, and we of course have to pass the request along.
2:04 And this is our decorator that we can use to authorize our api calls. How do we use it— super simple, we just use @auth.require_api_key
2:13 and this function will never even get called unless we've already made it through the authorization process
2:19 and along the way we've set the request.api_user so we can do things like request.api_user.name and api_key and so on.
2:27 This is definitely not the only way to set up authorization for apis, but it's a very common one and very easy to do,
2:36 easy for you and easy for people consuming your API.