SSO Not working with API when using swagger or postman - laravel

I am trying to make a single login session over the entire project environment. I want users to have only a single sign-on session, let it be on the website, web app, or application connected via api or web guards.
The website and web app worked fine but when I tried calling the same function by API using postman or swagger I get 500 Internal Server Error. I am not sure why am I getting it because there is no such error displayed in the response.
authenticated($request, $this->guard()->user()) in Login Controller
protected function authenticated(Request $request, $user)
{
if (! $user->isActive()) {
auth()->logout();
return trans('auth.login.deactivated_account');
}
event(new UserLoggedIn($user));
if (config('access.users.single_login')) {
auth()->logoutOtherDevices($request->password);
}
}
Sessions get distracted when done in website and web app but when using postman or swagger it's not working, I am not sure why?

Related

Laravel Jetstream/Sanctum API authentication

I have been working with Laravel since version 5.X up to version 8.X but always use it for backend API (never used blade template), and always pair it with VueJS on the front-end using JWT authentication (also never messed with any other authentication method).
Now with Laravel 9 and Vue 3, Im trying to use native Laravel Jetstream that uses SANCTUM and Vue+Inertia JS, and I'm quite lost with the authentication process. with JWT method, once the user succesfully login on the browser, all api request to Laravel will be authenticated using Authoraziation header. but this seems a different case with Sanctum.
After deploying and installing Jetstream and completed all the set-up. I created a user and loggedin with that user details. and I notice few things, there is a default API route
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
when I tried to directly access my.domain/api/user I notice it was redirected to GET /login
then redirected again to GET /dashboard
I then created a test api route using below
Route::get('test', function( Request $req) {
dd( [
'test' => $req->all(),
'user' => auth()->user(),
'request' => $req
] );
});
and I notice this request is not authenticated even when the cookies is present on the request as Im when I'm alraedy logged-in on the same browser, the auth()->user() is null.
I tried adding auth:sanctum middleware
Route::middleware('auth:sanctum')->get('test', function( Request $req) {
dd( [
'test' => $req->all(),
'user' => auth()->user(),
'request' => $req
] );
});
but having sanctum middle behave the same as the api/user where if i open api/test directly on the browser, it gets redirected to GET /login then redirected again to GET /dashboard and I'm quite lost at this point. I tried reading the docs and it says I have to do a separate authentication for this that would issue an API token and I was thinking I might better be going back with using JWT auth as it seems a lot easier to deal with.
So my question is; How can I authenticate an API end-point without having to redirect it to /login then /dashboard if the user is already logged in on my application using default sanctum authentication.
My goal is just to simply create /api/test that will be automatically authenticated if user already loggedin on the same browser and return the data I set on its return value and not doing any redirects.
Appreciate any help
I have got the same issue with laravel8
Jetstream and inertia vue3.
Am looking for the solution since 3 days posting messages on discord, searching on YouTube and more but nothing.
When i make an api call from your SPA to laravel, i got UNAUTHENTICATED response.
on postman you need put
headers
Accept = application/json
this tells your application know how works with Json
and go stop redirect to "Login"

Laravel returns unauthorized with second request

I'm trying to create SPA. I use Laravel API for backend and Nuxt.js for frontend. I want to authenticate users via Laravel Sanctum. I run backend on localhost:8000 and frontend on localhost:3000. SANCTUM_STATEFUL_DOMAINS is set to localhost:3000, SESSION_DOMAIN is set to localhost and SESSION_DRIVER is set to cookie.
I created login and logout in my app and everything works great until I make first request after logging in. I just wanted my app to return all users:
Route::middleware('auth:sanctum')->get('/users', function() { return User::all(); });
but it returns 401 unauthenticated. I don't know why is that happening. The route used for returning logged in user uses the same middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
and works perfectly (Nuxt returns logged in user with every page change). I called users route with axios:
axios.get('http://localhost:8000/api/users')
What can cause this problem? This is very frustrating because I struggled a lot just to get the login and logout working.
I also thought about running API on api.domain.test and frontend on domain.test but is it possible to hook up a domain like that to Nuxt locally?
It returns unauthorized because the call to the endpoint doesn't have access token of the user.
The idea is that when you login auth:sanctum returns access token to the client so that it can use it to access the data in all of it's next calls.
To do that you need to use authentication module in nuxt check this
The problem you are going to face next is that SPA doesn't have middleware so you need to set your app as universal instead of spa to be able to use the middleware in the client side

Laravel login with Facebook

Frequently got this error when trying to login with Facebook.
Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https://
This is what I got.
Provider function:
public function redirectToProvider()
{
return Socialite::driver('Facebook')->redirect();
}
Call back function:
public function handleProviderCallback()
{
$user = Socialite::driver('Facebook')->user();
}
there are two ways to fix this
First one is to create a virtual host (HTTPS)
The easy one is to disable ENFORCE HTTPS in your facebook app settings
APP -> Facebook login -> Client OAuth Settings

Blacklisting JWT tokens

For my API i'm using this package tymondesigns/jwt-auth with Laravel.
Security is very important! Tokens will be blacklisted after every request with a new token in the response. While doing some tests using both middlewares jwt.auth and jwt.refresh on the same route I get mixed results. Sometimes it works OK, sometimes I get a 401 unauthorized and have to login again.
I'm using the jtw.auth middleware so I can make use of Auth::user() in my app.
$api->group(['middleware' => ['jwt.auth', 'jwt.refresh']], function ($api)
{
// Protected routes here
});
Does someone have a working example for this?

Codeigniter RESTful web API for web and mobile applications

I'm having application with running good in codeigniter, mysql and jquery. Currently we are planning to evaluate our web application with mobile application. So we planned to develop web application, android, ios and blackberry. Everything is native application.
For everything we planned to develop codeigniter restful API (This is server for all the client web and mobiles).
For web application we planned to develop client with angular js. But every client access web api server only. My codeigniter controller now looks like API.
My question is,
1.Is this good idea to create single server for all the client both web and mobile
2.How to create unique authentication for both web and mobile apps
Because in web app we have the session but in mobile there is no session. So how to create authentication uniquely for both apps.
I have planned to send a token to client, once login get successful. And then after for each and every request to server, the client will send a token with the request header. I have no idea of how to do the same for mobile apps, as web app having session, and hence we can save the token into session variable in server. But in-case of mobile app, how to create server variable and maintain the tokens.
Please anyone help me to get clarify my doubts.
You can check out Codeigniter REST Controller
(https://github.com/chriskacerguis/codeigniter-restserver/tree/master/application). It has different methods POST, GET etc
For Authentication:
If a server get a login request, if the login parameters are valid allow the user to login, at the same time update the user db column with a session id (this is not php session id) - create a session with user id+time+some random string sha 1 or some other encryption. And valid this session with all other request.If session is not matching the services return invalid session message.
If a server get a login request from a user even if there is session exist, regenerate the session and update corresponding column in db, this will make previous session invalid.
And also, we can share a API KEY (known to developer of web and app) as http header parameter. If API key matches then only the request proceeds. The mentioned codeigniter controller has the option to set API key.
Hope it is clear..
<?php
class Api_ci extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Api_model');
$this->load->helper('text');
}
// code for login *api*-------------------------------
public function login_api_ci(){
$email = $this->input->get('email');
$pass = $this->input->get('password');
$query = $this->Api_model->login_api($email,$pass);
echo json_encode($query);
}
}
?>
<?php
class Api_model extends CI_Model{
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->database();
}
// code for login api
public function login_api($username,$password){
$query = $this->db->query("SELECT * FROM `host_users` WHERE `email` = '$username' AND `password` = '$password'");
return $query->result_array();
}
}
?>
After these process, your API URL your domain name and / class name, class function:
www.example.com/Api_ci/login_api_ci?email=gaurav#gmail.com&password=1234567899
Output like this :
[{"id":"112","f_name":"gaurav","l_name":"singh","email":"gaurav#gmail.com","mob":"1234567899","password":"1234567899","img":null}]
Just to update this thread, I feel like creating a RESTFUL web API using Codeigniter is overkill, there's a lot of things that are unnecessary unless you are building a monolith system.
I prefer just creating a simple API without framework is better and lighter, it can also easily be scaled because nowadays microservices has more benefits than a monolith type of development.

Resources