در حال بارگذاری ...

Introducing Laravel Passport0:00

Hi, this is Taylor Rotwell, back with another Laravel screencast. In this screencast, I'd like to introduce you to Laravel Passport. Passport is a new optional package for Laravel that makes it very painless to do OAuth2 servers. So, let's go ahead and just dive right in. I've got a fresh Laravel application, and I want to walk you through implementing a full OAuth2 server in this application. Now, all I've done is pull in Laravel Passport in my composer.json file and run npm install, since both of those operations can take a little time. Alright, so I've got my fresh application, so let's go ahead and get started. The first thing we want to do is register the Passport service provider in our config/app.php file. And down here near the bottom is our service provider listing.

Register Provider and Migrate0:36

The first thing we want to do is register the PassportServiceProvider in our config/app.php file. And down here near the bottom is our service provider listing. And right here, I can just add Laravel\Passport\PassportServiceProvider. And that's just going to register the classes and the migrations that Laravel Passport needs. Now, once that's done, we can go ahead and migrate our database. This is a new feature in Laravel 5.3, where service providers can actually register their own migration directories. So, if I pull up my console, I can run php artisan migrate. And you can see I get my typical users and password_resets table, but I also get several new OAuth tables that hold my clients, authorization codes, access tokens, and so on. Alright, now that our database is migrated, we want to run another artisan command called passport:install.

Install Passport and Update User1:17

but I also get several new OAuth tables that hold my clients, authorization codes, access tokens, and so on. Alright, now that our database is migrated, we want to run another artisan command called PassportInstall. So, I'll do php artisan PassportInstall. And what this does is it generates an encryption key that lets Passport securely create access tokens. And it's going to ask us to make a personal access token client. And we'll talk a little bit more about this later, but for now, we'll just go ahead and accept the default value. Once we've run the install command, we're ready to jump back into our code. Let's go to our User model, and we need to add one trait to this model, and that's the HasApiTokens trait. So, I'm going to import that trait from Laravel Passport HasApiTokens, and just add it to my traits on my User model here. And this trait just provides a few useful functions for accessing the current access token for the authenticated user,

Configure Routes and API Guard2:00

So, I'm going to import that trait from Laravel Passport HasApiTokens, and just add it to my traits on my User model here. And this trait just provides a few useful functions for accessing the current access token for the authenticated user, and it lets you examine the scopes that are available to that access token. Alright, now that that's done, let's jump over to our AuthServiceProvider. And right here at the top, I'm going to import Laravel Passport Passport, which is the main Passport configuration class, and I'm going to say Passport::routes(). And what that does is it registers the routes that we need to issue access tokens, to authorize requests, to access an account, and so on. So, it registers all those routes and controllers that Passport needs to operate, and it saves you a lot of work because Passport is providing a full JSON API that your front end can hook into. Now, the last configuration item we need to do is in our config/auth.php file.

and it saves you a lot of work because Passport is providing a full JSON API that your front end can hook into. Now, the last configuration item we need to do is in our config/auth.php file. So, I'll go to config/auth.php, and I just need to switch out the API guards driver from token to Passport. And that's going to tell the authentication services in Laravel to use the Passport driver when we're authenticating API requests. Alright, and that's all I need to do to set up Passport, so it's fully configured and set up now at this point. Now, what I want to do is go ahead and run php artisan make:auth, so that I can scaffold out the authentication features of Laravel so that we can create a User to log in with. Alright, now in my browser, let's refresh this page and make an account. Now, let's go ahead and create a User for myself and log into the application. Now, when we're doing OAuth, we need a way for Users of your application to register their own applications that are going to consume your API.

Publish and Add UI Components3:38

Now, let's go ahead and create a User for myself and log into the application. Now, when we're doing OAuth, we need a way for users of your application to register their own applications that are going to consume your API. This is typically called creating a client or an OAuth client. Alright, now typically we would have to build a full front end dashboard to let your users create clients, create access tokens, revoke access tokens, revoke clients, and so on. And that can be a lot of work. So, Passport actually ships with pre-built view components that we can just drop anywhere in our application and get started right away. And they serve as a great starting point for either your own implementation or something you can just maintain in your application and let Passport take care of it for you. Now, to get started with these components, I need to publish them to my own application. So, we can do that via artisan. Let's go back to our console and we'll do php artisan vendor:publish.

So, we can do that via artisan. Let's go back to our console and we'll do php artisan vendor:publish. And we're going to do a publish tag, which lets us publish a subset of resources that can be published from all our packages. And this tag is going to be passport components. Alright, now let's go back to our code and see what this did. So, if I go to my resources, assets, js, components, you'll see there's a Passport directory, which contains the view components to help us get started here. Now, I need to register these components with a view. So, I'm just going to grab some code that we can drop into our app.js file that will register these components. And I can put this right under the example component that ships with Laravel 5.3. So, once these components have been registered in our app.js file, we can run the gulp command to recompile.

And I can put this right under the example component that ships with Laravel 5.3. So, once these components have been registered in our app.js file, we can run the gulp command to recompile. And this is going to compile those assets, those view components, which are really great single file components that contain their own template and JavaScript to manage a certain task. Alright, now once that's compiled, we're ready to just drop them into our application. And this is really cool. We can actually just go to the home.blade.php. This is the UR logged in screen that, if you'll remember, we're seeing once we log into the application. And we're just going to replace this with our components. Alright, so we're just dropping in the PassportClients component, which lets you create clients. The PassportAuthorizedClients component, which lets you see which clients you've authorized to access your account and revoke access if necessary.

Alright, so we're just dropping in the Passport clients component, which lets you create clients. The Passport authorized clients component, which lets you see which clients you've authorized to access your account and revoke access if necessary. And the Passport personal access tokens component, which lets your users just generate a personal access token to experiment with your API. Alright, so once we've done this, we're ready to test this out in our application. So, let's go to the Chrome browser, refresh the page, and you can see we have a whole UI here ready to go for creating OAuth clients. Now, let's go ahead and create a client. I'll click the create new client, and we're presented with this modal window where we can create our client. I'm just going to call this consumer since it's a consumer of our API. Now, all clients need a redirect URL. This is where the user will be redirected after they approve the authorization request.

Create Client and Authorize6:50

Now, all clients need a redirect URL. This is where the user will be redirected after they approve the authorization request. So, I'm just going to do consumer.dev because I already have a little consumer app that we can play with. And I'm just going to redirect to /callback. Alright, so let's create this client. And you'll see that we have a client ID and a secret. And those are the two important pieces of information we'll need on the consumer side when we authorize requests to this application. So, let's remember this client ID and grab this client secret. And let's head over to a separate project, which is going to serve as our consumer. So, I'm going to go back to my console and go up a directory into my consumer project.

And let's head over to a separate project, which is going to serve as our consumer. So, I'm going to go back to my console and go up a directory into my consumer project. And I can just plug in these values. So, clientId, clientId, and our clientSecret. Now, let me walk you through this consumer client and talk a little bit about it. The consumer is going to redirect to our Passport application, that's our OAuth2 server, to the /oauth/authorize. And remember, this route is provided by that fantastic Passport::routes method that automatically set up the routes and controllers we needed to build a fully functional OAuth2 server. We're going to send over our clientId and our redirectUri and the responseType, which is code, which is saying we want an authorization code that we can exchange for an access token. Alright, now when we redirect to Passport, let me show you how this works. So, let's go to our Chrome and pull up our consumer application.

Alright, now when we redirect to Passport, let me show you how this works. So, let's go to our Chrome and pull up our consumer application. You'll see that when we're redirected to Passport, Passport automatically takes care of presenting this screen where we can approve or deny a request for authorization. In this case, it's saying that the consumer client wants to request permission to access our account. You've probably seen this if you've ever done login with GitHub or login with Facebook, where you're redirected to Facebook and need to approve the request to access your account. Alright, so in this case, we can authorize that request and you can see that we get a JSON response, which includes an access token here. Alright, so it was that easy to set up a fully functional OAuth2 server in Laravel in just a few minutes. And right here we have the access token and down here we have the refresh token and we have information about how long the tokens last and when they expire. So, just like that, we've already set up a fully functional OAuth2 server. Now, if I refresh this screen, you can see that it does show that I've authorized the consumer application to access my account and I can revoke that permission if necessary.

Generate Personal Access Tokens9:12

So, just like that, we've already set up a fully functional OAuth2 server. Now, if I refresh this screen, you can see that it does show that I've authorized the consumer application to access my account and I can revoke that permission if necessary. So, it's just that easy to build an OAuth2 server with Laravel 5.3 and Passport. Now, one last thing I do want to talk about is personal access tokens. Now, sometimes if you just want to let your users experiment with your API, you don't want to force them to go through the whole redirect flow just to get an access token. It's really convenient to let your users create an access token right here in your User interface. GitHub ships a feature like this that's also called personal access tokens that lets you just create access tokens in the interface to experiment with the GitHub API and Passport lets your application offer that same functionality. So, if I click create new token, all I need to do is just assign my token a name. We'll just call it experiment. All right, and that's going to just give me the access token directly that I can just copy into my clipboard and use in a program to test out and experiment with the API, something like Postman.

We'll just call it experiment. All right, and that's going to just give me the access token directly that I can just copy into my clipboard and use in a program to test out and experiment with the API, something like Postman. All right, so we've got that token copied, and you can see here I can delete it or revoke it whenever I want. But let's go ahead and jump into Postman, which is an API REST client. All right, I'm just going to remove that old token and paste in my new one, and we're making a request to passport.dev/api/user. So, before we hit this, let's go ahead and check that route out. All right, in our api.php file, this is a new routes file in Laravel 5.3 specifically for your API routes. It already has the API prefix applied, so we can just specify the /user portion of the URI, and it already has the auth:api middleware applied. So, all of these routes are going to be automatically authenticated using our API guard. All right, and all it does is return information about the current user.

Consume API from Frontend11:02

So, all of these routes are going to be automatically authenticated using our API guard. All right, and all it does is return information about the current user. So, let's go ahead and hit this route. We've got our fresh API token pasted in, and you can see we get a JSON representation of the user every time we hit the route. So, we are being authenticated, and if we just garble up this token to where it doesn't make any sense, you can see that we get an unauthenticated error. Now, there is one more aspect of Passport that I'd love to show you, and this involves how you consume your own API from your front end. All right, so let's go back to our code. We have this /user API route, and we'd love to be able to consume it from our own UI, but this can sometimes be cumbersome because how do we get an access token to pass to our own API? And it's just extra headache that you have to think about when you're building an API.

but this can sometimes be cumbersome because how do we get an access token to pass to our own API? And it's just extra headache that you have to think about when you're building an API. Passport makes this really easy. So, first, let me demonstrate what I'm talking about. Let's go to our example view component. All right, and within this view component's ready function, let's make an API call to api/user, and then let's just console.log the response data. All right, now we need to go ahead and run a gulp to compile this change to our view component. So, let's go ahead and run gulp there. All right, and now you'll notice that we're not passing any access token,

So, let's go ahead and run gulp there. All right, and now you'll notice that we're not passing any access token, so we would typically expect to get some kind of unauthorized error when we make the call to this API route. All right, so let's drop this component into our template. This is just the example component, which ships with Laravel 5.3, and I'm going to open my inspector here and refresh the page, and you can see we do. We get a 401 unauthorized error, just like you would expect, and this is not surprising because we're not passing any access token to the back end, and this is where the headache comes in. How can we get an access token so that we can just call our own API?

and this is where the headache comes in. How can we get an access token so that we can just call our own API and get the JSON data that we're sharing with outside applications? And that's a really great way to develop because you can share the same API with your web front end as you consume from your mobile client or from your third-party SDK. All right, so let's go ahead and work out this problem. Passport ships with a middleware that will solve this entirely for you, so let's go to our HTTP kernel. And in our web middleware group, which is used for all of our web front end routes, let's add a new middleware. Laravel Passport HTTP Middleware Create Fresh API Token. Now, what this does is for every web request, it will attach a cookie that contains an encrypted JWT token,

Laravel Passport HTTP Middleware Create Fresh API Token. Now, what this does is for every web request, it will attach a cookie that contains an encrypted JWT token, and that token has the CSRF token embedded within it as well as other information about the current user. And that lets us securely authenticate you when you make requests to your own API. The Passport Guard will first look for the authorization header, and if it doesn't find it, it will look for this encrypted JWT token cookie. All right, so we've added this middleware. Let's go ahead and go back to our browser, refresh the page, and you can see successfully we got our user information from our API, even though we didn't ever have to worry about passing any API tokens from our front end.

and you can see successfully we got our User information from our API, even though we didn't ever have to worry about passing any API tokens from our front end. We can just seamlessly and really easily consume our own API using Passport. Now, in just these few minutes, we've implemented a full OAuth2 server, and we're now consuming our own API really easily with Laravel Passport. I think it will save you a lot of time, and I think you'll really love it.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟