Passing accessToken from frontend to PHP API - laravel

I've been trying to get authentication working (described below) in my laravel application, following these two tutorials:
https://auth0.com/docs/quickstart/webapp/laravel/01-login
https://auth0.com/docs/quickstart/backend/laravel/01-authorization
On the frontend (angular app):
User clicks log in button and taken to auth0 login page
The user logs in and is redirected back to the callback with the accessToken
The access token is stored on the frontend and passed to Laravel API each request.
On the backend:
User makes a request to my http://localhost/api/route passing the accessToken in the authorisation header
Laravel validates the user is logged in and valid.
Laravel allows access to that route
It works to an extend, but when I try to use postman to access the protected route by passing the accessToken I get the error:
"message": "We can't trust on a token issued by: https://myprojectname.au.auth0.com/."
Is my workflow correct? What am I missing?
Thanks!

Just in case if somebody facing with the same issue. The authorized_iss must contain a trailing slash.
In the laravel-auth0.php file the field,
'authorized_issuers' => 'https://myprojectname.au.auth0.com/'
should be in this form.

Related

Laravel Sanctum 401 error after on reloading

I am using Laravel Sanctum's API Tokens to authenticate requests from a React application. I don't use SPA Authentication and cookies.
For now, the Laravel sessions are managed with files.
After you login, you get a token, and with the given token, you can call APIs successfully. But if you refresh a page, even with the same token, API calls fail with 401 status code and the following message:
{
"message": "Given authorization token is not valid. Please try to login again."
}
It works fine on my localhost. It only happens on a live site, and after you refresh a page.
The Laravel backend serves only APIs, so it defines routes in api.php only. All these routes are using auth:sanctum middleware (of course, with an exception of /login route).
The following line is disabled in Kernel.php for the api middleware group:
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class
Any thoughts on how to fix this?

Laravel Passport Authorization Code Grant on Backend System

I am trying to think of the best way to implement the oauth authorization code grant in my API codebase.
I cant use the standard routes passport generates because I have no frontend so I can't create sessions or anything to store user data/codes etc...
Instead I was planning to use the following workflow -
User redirects to frontend (seperate codebase) https://{frontend}/oauth/authorize endpoint passing through the require URL params (client_id, redirect_uri)
Once this page is hit a request is made to my backend system, this checks to make sure the client_id and redirect_uri match a record in the database. A success response is returned if a record exists.
On the frontend because the backend response was a success they can now enter their username and password, a request is made to my backend system again to check these details are correct. If everything is correct the backend returns an auth code in the response data
If the login response was successful the frontend redirects the user back to the callback URL with the code url param
External app then makes a request to https://{backend}/oauth/token which checks the code and if its a success returns an access_token, refesh_token and expires_in
My question is does this flow look correct for an app with seperate frontend/backend codebases. Just to clarify my frontend codebase is using the laravel password grant which is working fine so this question is only for integrating external systems via oauth.
I was also wondering when the backend generates the auth code where should this be stored which can then be checked again when the /oauth/token request is made?

How to resolve unauthenticated issue in Postman GET Request

I used Laravel-8 for rest api. The route is shown below:
localhost:8888/myapp/server/api/v1/admin/role
It is a GET Request.
When I send it on POSTMAN, I got this error:
401Unauthorized
{
"message": "Unauthenticated."
}
In my route I have:
'middleware' => ['auth:api']]
The reason is because I don't know how to add the Login details. email: akwetey#gmail.com, password: mypass
How do I achieve this?
Thanks
This person walks you through the process nicely and should get you setup.
https://coding-lesson.com/api-authentication-with-laravel-passport/
Basically you need to:
Get to your login api, probably something like: localhost:8888/myapp/server/api/v1/login
Create a POST request to the login API, select the Body tab and define key values for you Email and Password
Then run the request and copy the AccessToken value from the results
Now with your API above, select the Authorization tab, choose Bearer Token as the Type and paste in your AccessToken value for the Token field
You should also go to your Headers table and define Accept and Content-Type keys, both with values of: application/json
Of course you'll want to then change all this to use variables after you get it right, so you don't have to keep repeating this with all your new API calls.
To fetch data behind protected routes you need to provide a token that will verify that the user who made the call is authenticated.
Then you have to provide the token in Authorization section of postman.
I assume you know the difference between Post and Get. Laravel works a little different then regular PHP, let me tell you how.
In order to access the protected routes you'll have to first access the token from login route. By sending the required data in .
Once that's done it'll return the token which can be used to access the protected routes under admin or auth middleware.
In your case you're accessing localhost:8888/myapp/server/api/v1/admin/role which is a protected route under admin middleware. You'll have to first access token and then send token with the get request to fetch the required data.

Magic Link login with Laravel Sanctum

For my project I have a set of users that should only be able to login by requesting a Magic Link. So they have an email address but no password. To avoid security issues, my goal was to get this working without having to save an authentication token in LocalStorage.
I've tried setting this up the following way with Laravel Sanctum:
When requested, I create a token for the user and email them the plaintext version.
The user would open the link containing the token in the querystring.
I would attach the (Bearer) token with the Authorization Header.
The next step (I assumed) would be to call a custom /api/login endpoint that uses the 'auth:sanctum' middleware. The Bearer token would authenticate the user and then I would manually login the user with Auth::login(). After this the active Session would be used to authenticate the user, thus avoiding having to save the token in localStorage.
But I can't call the Auth::login() method manually without getting an error (BadMethodCallException: Method Illuminate\Auth\RequestGuard::login does not exist.).
I can't figure out why this isn't working, or maybe I am going at this all wrong?
if you sending Sanctum token to user via email so in 1st request you will get token from url and you can use that token to login to application like this
use Laravel\Sanctum\PersonalAccessToken;
public function login(Request $request)
{
$personalAccessToken = PersonalAccessToken::findToken($request->token);
$user = $personalAccessToken->tokenable;
auth()->login($user);
return redirect('/');
}

Unable to get authenticated user using Laravel 5.8 and Auth0

I have a Laravel 5.8 API that I want to secure using Auth0. So far I've followed every step of this tutorial:
On the front side, Login/logout links are currently implemented in Blade, and this works fine, though the rendered content on the page is done using Vue Router, making AJAX requests to the API for the data.
The default User model in Laravel has been modified to store name, sub, and email per the tutorial, and this populates as well.
The API endpoint is secured using the jwt middleware created during the tutorial, and I can successfully submit a GET along with a hard-coded Bearer auth token in Postman and get a good response.
However, at some point I'd like to be able to pass an access token off to Vue so it can do its thing, but I'm unable to get the current authenticated user. After hitting Auth0, it redirects back to my callback route with auth gobbledlygook in the URL. The route in turn loads a controller method, and everything even looks good there:
// Get the user related to the profile
$auth0User = $this->userRepository->getUserByUserInfo($profile); // returns good user
if ($auth0User) {
// If we have a user, we are going to log them in, but if
// there is an onLogin defined we need to allow the Laravel developer
// to implement the user as they want an also let them store it.
if ($service->hasOnLogin()) { // returns false
$user = $service->callOnLogin($auth0User);
} else {
// If not, the user will be fine
$user = $auth0User;
}
\Auth::login($user, $service->rememberUser()); // "normal" Laravel login flow?
}
I'm not an expert on the framework, but the last line above seems to start the "normal" Laravel user login flow. Given that, shouldn't I see something other than null when I do auth()->user(), or even app('auth0')->getUser()?
Try using a simple tutorial if you're a beginner, I would recommend this
It uses a simple JWT package to create a jwt token which you can get when the user authenticates.
JWTAuth::attempt(['email'=>$email,'password'=>$password]);

Resources