showing {"error":"Unauthenticated."}, while calling larvel API in Laravel 5.4 and passport version: v1.0.9, using ajax call.
Calling from route api:
Route::get('category/get_tree_data', 'CategoryApiController#getTreeData')->middleware('auth:api');
If you set up Laravel Passport properly, you should have this in your view:
You need to create a client, that client has a client id and a client secret.
Now you need to open your consumer app which shall contain your client id and your client secret.
It looks like this(you have to change the token and id to your specific one):
class OAuthController extends Controller
{
public function redirect()
{
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://localhost/app/public/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://localhost/app/public/oauth/authorize?' . $query);
}
public function callback(Request $request)
{
$http = new Client;
$response = $http->post('http://localhost/app/public/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3, // from admin panel above
'client_secret' => 'BcTgzw6YiwWUaU8ShX4bMTqej9ccgoA4NU8a2U9j', // from admin panel above
'redirect_uri' => 'http://localhost/app/public/callback',
'code' => $request->code // Get code from the callback
]
]);
return json_decode((string) $response->getBody(), true);
}
}
Now you need to call that consumer app and authorize your application.
If that worked you get an access token + a refresh token.
It should look like this:
Now you can test this using a program like postman.
You basically call your get route and add the access token, which gives you access to the api, like this:
If you have any more question I recommend reading the docs.
Thus I highly recommend watching following video from Taylor Otwell.
Of course you can give me a comment aswell if you have any more questions.
Add this code inside your /resources/assets/js/bootstrap.js file
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
working perfectly...
I have the same issue with Laravel 5.8 when calling /api/user on auth:api middleware, I've tried to call the API url using Postman but got unauthenticated message
And I am able to fixed it by changing the hash value to false in config/auth.php file
// routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
// config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false, // <-- change this to false
],
],
I faced the same issue.
In my case, I was caching generated token after user login.
$token = $user->createToken('API'.'-'.strtoupper($user->username).'-'.'-X-AUTH-TOKEN', [$this->scope]);
Cache::add(strtoupper($user->username).'-'. 'X-TOKEN', $token->accessToken, $expiresAt);
After debugging, tried clearing cache
Cache::clear();
and it's working now.
Related
I want to create an authentication system with laravel , passport and vue js . Which is the best choice
1 - laravel
public function login(Request $request)
{
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => $request->username,
'password' => $request->password,
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
1 - vuejs
axios.post('/login', {
'username': 'xxxxxx',
'password':'xxxxxxxxx'
})
.then(response => {
//login
}).catch(error => {
//error
})
2-vuejs
axios.post('/oauth/token', {
'username': 'xxxxxx',
'password':'xxxxxxxxx',
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
})
.then(response => {
//login
}).catch(error => {
//error
})
In Solution 2, is it dangerous to put the client_secret on the client side?
Not at all. Keep it in a .env file and make sure to put it in your .gitignore
I would prefer Solution 1. In Solution 2 everyone can read the client_secret and pretend to be the client.
I would suggest option 3: using passports built in JS authentication.
You authenticate using the standard auth flow that ships with Laravel. Then add the \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class middleware on the routes that serve VueJS. Make sure your axios is configured to include the CSRF token by default. If you use the app.js that ships with laravel then this is already done for you. You can then make your axios requests as usual. (making sure to include the CSRF token. Th.
I would suggest you to use solution 1. It protects your OAuth service keeping it hidden and not reacheable. In addition you should implement a mechanism to refresh the tokens.
I am using a Laravel version 5.5 using Passport for authentication.
I have successfully create the token and can access it using the auth:api middleware.
But whenever user login into system it create new token for that user. I just want to refresh user last token and send it back instead of creating a new token.
I have used the following code to generate auth token
$token = $user->createToken('string-'.$user->id)->accessToken;
It generate the token with 1075 characters but when i checked in database table oauth_access_tokens it shows me the token with 80 characters.
How can i get last generated token using 80 character token and refresh it and send it back?
Thanks in Advance
If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued. In this example, we'll use the Guzzle HTTP library to refresh the token:
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'the-refresh-token',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.
I've done something like.
Created an endpoint for grant refresh token.
and in my controller,
public function userRefreshToken(Request $request)
{
$client = DB::table('oauth_clients')
->where('password_client', true)
->first();
$data = [
'grant_type' => 'refresh_token',
'refresh_token' => $request->refresh_token,
'client_id' => $client->id,
'client_secret' => $client->secret,
'scope' => ''
];
$request = Request::create('/oauth/token', 'POST', $data);
$content = json_decode(app()->handle($request)->getContent());
return response()->json([
'error' => false,
'data' => [
'meta' => [
'token' => $content->access_token,
'refresh_token' => $content->refresh_token,
'type' => 'Bearer'
]
]
], Response::HTTP_OK);
}
I am trying to do a route /api/user/signin and inside of controller to make a Guzzle HTTP post to /oauth/token. Great but the server stall. I found this: https://stackoverflow.com/a/46350397/5796307
So how I should do? How to call /oauth/token without a HTTP request? I can "create" a request class and pass to that function?
No need to use Guzzle or file_get_contents, create a new HTTP request from within the controller function and route it through the framework:
public function signin (Request $request) {
// get an appropriate client for the auth flow
$client = Client::where([
'password_client' => true,
'revoked' => false
])->first();
// make an internal request to the passport server
$tokenRequest = Request::create('/oauth/token', 'post', [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $request->input('email'),
'password' => $request->input('password')
]);
// let the framework handle the request
$response = app()->handle($tokenRequest);
// get the token from the response if authenticated, other wise redirect to login
}
I am working on a project where 3rd party apps can access data from Laravel server. I also have created a client application in laravel for testing.
Following code ask for authorization and its working fine.
Route::get('/applyonline', function () {
$query = http_build_query([
'client_id' => 5,
'redirect_uri' => 'http://client.app/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://server.app/oauth/authorize?'.$query);
});
How can I authenticate a user before authorization? Right now I can access data form server using this code.
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'fcMKQc11SwDUdP1f8ioUf8OJwzIOxuF8b2VKZyip',
'username'=> 'ali#gmail.com',
'password' => 'password',
],
]);
$data = json_decode((string) $response->getBody(), true);
$access_token = 'Bearer '. $data['access_token'];
$response = $http->get('http://server.app/api/user', [
'headers' => [
'Authorization' => $access_token
]
]);
$applicant = json_decode((string) $response->getBody(), true);
return view('display.index',compact('applicant'));
});
Although above code works fine but I don't think its a good way to ask username and password at client side.
I want to use this flow (Same as facebook allows)
Click To Get Data From Server
Enter Username and Password
Authorize App
Access data for authenticated user
Well that was a stupid mistake. It works fine with authorization_code grant type. My mistake was that I was testing both server and client in same browser without logout. So client was accessing its own data from server. Also this flow diagram really helped me to understand the process of passport authorization.
http://developer.agaveapi.co/images/2014/09/Authorization-Code-Flow.png
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 5,
'client_secret' => 'fcMKQc11SwDUdP1f8ioUf8OJwzIOxuF8b2VKZyip',
'redirect_uri' => 'http://client.app/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);});
I am trying to use an OpenID Connect library in PHP, I have downloaded and tested this one: https://github.com/jumbojett/OpenID-Connect-PHP
It worked perfectly, but then I started a Laravel 5.4 project and added the library to it. My idea is to use a middleware to redirect the user to the library and authenticate the user when the 'admin' page is requested.
But when the program reaches a 'redirect' method the session is lost, which didn't happen when I wasn't using Laravel.
This is the web.php file
Route::group(['middlware' => 'web', 'auth'], function () {
Route::get('admin', 'KeycloakController#auth');
});
This is the kernel.php file
protected $middlewareGroups = [
'web' => [
\MiddlewareTest\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\MiddlewareTest\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
'auth' => [
'keycloak' => \MiddlewareTest\Http\Middleware\Keycloak::class,
],
];
When the controller is reached, I call this method from another class
private function requestAuthorization() {
$auth_endpoint = $this->getProviderConfigValue("authorization_endpoint");
$response_type = "code";
// Generate and store a nonce in the session
// The nonce is an arbitrary value
$nonce = $this->generateRandString();
Session::put('openid_connect_nonce', $nonce);
// State essentially acts as a session key for OIDC
$state = $this->generateRandString();
Session::put('openid_connect_state', $state);
Session::save();
\Log::info(session('openid_connect_state'));
$auth_params = array_merge($this->authParams, array(
'response_type' => $response_type,
'redirect_uri' => $this->getRedirectURL(),
'client_id' => $this->clientID,
'nonce' => $nonce,
'state' => $state,
'scope' => 'openid'
));
// If the client has been registered with additional scopes
if (sizeof($this->scopes) > 0) {
$auth_params = array_merge($auth_params, array('scope' => implode(' ', $this->scopes)));
}
$auth_endpoint .= '?' . http_build_query($auth_params, null, '&');
$this->redirect($auth_endpoint);
}
But, when the browser goes to that URL in the 'redirect' method, the session is lost - I don't know why.
Please help me to understand why is this happening.
Thanks in advance.