Axios post form data with user id of Logged in user - reactjs

i want to post my form data using axios.post with the current user login id.
axios.post('http://localhost:8000/api/add-property/',
formData, {
headers:{
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': 'http://http://127.0.0.1:8000',
'Access-Control-Allow-Credentials': true,
}
}
).then(function(response){
console.log(response.data.message)
}).catch(function(error){
console.log(error)
});
kindly tell me about these things ?
what should be the api url to add some data with the id of logged in user ?
how to get the current logged in user id ?
my backend is in laravel and my store function controller is something like this :-
public function AddProperty(Request $request, $id) {
$validator = Validator::make($request->all(),
[
"agency_name" => "required",
"agency_location" => "required",
// my rest of validations
]
);
if($validator->fails()) {
return response()->json(["status" => "failed", "validation_errors" => $validator-
>errors()]);
}
//--------------------get user id---------------------------------------------------
$user = array();
$user = DB::table('users')->where('id', $id)->first();
$user_identification = $user->id;
//----------------------------------------------------------------------------------
$agency_name = $request->input('agency_name');
$agency_location = $request->input('agency_location');
$user_id = $user_identification;
$propertyArray = array(
'agency_name' => "$agency_name",
'agency_location' => "$agency_location",
'user_id' => $user_identification
);
$property = AddProperty::create($propertyArray);
return "property added succesfully with id:".$property->id;
my route for add property is :-
Route::post("add-property/{id}", "AddPropertyController#AddProperty");
when i pass id from postman it enters data into the database i am confused with how to get the id from the react and pass it in the post api and the enter the data in my db.
kindly someone help me and thanks in advance

If you are using laravel authentication you can simply call
$user = Auth::user();
to retrieve the authenticated user
If you are not using the laravel authentication, well it depends on how you implemented that

Save the logged in user object or the auth(bearer token) in the local storage of the browser.
Then when sending with the post api simply use that token or user id in the header of your api.
You can use the local storage solution like this:
var userObj= JSON.parse(localStorage.getItem('userObj'));
Or you can use react js props solution in componentWillReceiveProps get the logged in user.

Related

What is the best way to save token (JWT) in cakephp 4?

I have a project and I made the backend using nodejs.
I made a user registration module and the authentication generates a token!
This token will need to be used in other requests where the user must be logged in.
What is the best way to store this token on the frontend using cakephp 4?
Is there any component? Is it safe to store this token using the session?
I would appreciate it if someone could help analyze this case.
This is my authentication method:
public function login()
{
$http = new Client();
if ($this->request->is('post')) {
$response = $http->post(
'http://localhost:8889/api/auth/login',
[
'email' => $this->request->getData("username"),
'password' => $this->request->getData("password"),
]
);
if ($response->getStatusCode() == 401) {
return $this->redirect($this->referer());
}
if ($response->isOk()) {
$json = $response->getJSON();
return $this->redirect(['action' => 'home', 'controller' => 'Pages']);
}
}
}
Return 200 contains an accessToken.
The best way to store the token is with an HttpOnly Cookie.
According to the Microsoft Developer Network, HttpOnly is an
additional flag included in a Set-Cookie HTTP response header. Using
the HttpOnly flag when generating a cookie helps mitigate the risk of
client-side script accessing the protected cookie (if the browser
supports it).
If you store it in a LocalStorage/SessionStorage then it can be easily grabbed by an XSS attack (from Javascript/Client side)
The CakePHP 4 way to do it is like this:
https://book.cakephp.org/4/en/controllers/request-response.html#creating-cookies
$cookie = new Cookie(
'jwt_token', // name
'token', // value
new DateTime('+1 hour'), // expiration time
'/', // path
'example.com', // domain
true, // secure only?
true // http only -> this is what you need
);

Authorize request to API by React

I want to use Santum with Laravel and I have a problem with Authorize. Sanctum works becouse I can take response if I send request via Postman. But I don;t understand how authorization works in React. Look at my code.
Here I generated token and save that in a cookie (I have httponly)
public function getToken(){
$user = User::first();
$token = $user->createToken('Authrization', ['server:update'])->plainTextToken;
Cookie::queue("Authorization", $token);
return $token;
}
In React I wanted use this token automatically (I read that this is possibe by withCreditional). Co I read this code
axios.get('http://localhost:8000/token')
.then(response => {
console.log(response.data.token);
});
const json = axios.get('http://localhost:8000/api/taks/all-tasks', { method: 'GET', withCredentials: true }).then(res => {
j = this.res.data;
return j;
})
console.log('Json' + json)
But I have an error (401). How can I authorize access to all-tasks route and route with the simples way?

laravel reactjs pusher: presence channel response is 302

I'm trying to make a reactjs application where an user can only login to one device at the time with the same user credentials. Unfortunately it isn't working.
I'm trying to authenticate a presence channel with reactjs to laravel but I get a 302 response.
reactjs:
Pusher.logToConsole = true;
var pusher = new Pusher("9028d58568392772df59", {
cluster: "eu",
forceTLS: true,
authEndpoint: '/broadcasting/auth',
auth: {
headers: {
'X-CSRF-Token': csrf_token
}
}
});
var channel = pusher.subscribe("presence-HandleCredentials");
channel.bind("sameCredentials", function(data) {
console.log(data);
alert(JSON.stringify(data));
});
channel:
Broadcast::channel('App.User', function ($user, $id = 1) {
return (int) $user->id === (int) $id;
});
broadcast:
public function boot()
{
Broadcast::routes(['middleware' => ['auth:web']]);
require base_path('routes/channels.php');
}
When I added this ['middleware' => ['auth:web']] I got the error. Before I added that I got a 403 error.
in the config\app.php I uncommented App\Providers\BroadcastServiceProvider::class,
Are there any tutorials out there that are build with laravel and reactjs for a presence channel?
does anyone know how to get past this 302 redirect?
Recently had the same issue with my laravel-websockets and laravel echo.
In my case I was unable to solve the 302, as Broadcast was unable to authenticate my logged in user. I was trying to subscribe to my private channel. So the workaround i found was that i manually created a POST route in web.php as "/broadcasting/auth". This is what my front-end requests to. So The updated code in web.php is as follows.
Route::post('/broadcasting/auth', function(Request $request){
$pusher = new Pusher\Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
array(
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => false,
'host' => env('APP_URL'),
'port' => 6001,
'scheme' => 'http',
)
);
return $pusher->socket_auth($request->request->get('channel_name'),$request->request->get('socket_id'));
});
I was creating my own websocket that is why i had to mention the host & port within the options, you don't need to use it if you are Using Pusher. You can also add other middlewares to the routes if needed.
You have to comment out the following line in app/providers/BroadcastServiceProvider:
public function boot()
{
// Broadcast::routes();
require base_path('routes/channels.php');
}
so that the request can reach my broadcasting/auth route in web.php.
Try this. now this should return a 200 when the broadcasting/auth is requested by your client end with response of an auth code. Do let me know if this solves your problem.

where and how to store laravel passport authentication token and send request from front-end with that token?

i've created a laravel passport api based authentication.and using react js as frontend.when i send login request with email,password my backend send me authentication token.now where should i store this token?? if i want store it in cookies how to do that?? and how to send this with frontend ajax request??
actually i'm totally new.so if this question sound stupid ,i'm sorry..
this is my login function:
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('AppName')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
You can save the token to local Storage on react js.It is one of the method to store and access the token.
localStorage.setItem("token", token value)

How to create Token-Based Authentication(oauth2) for AngularJS and Laravel Apps via passport

I created an web app which it uses laravel default registration(auth), I've tested passport oauth2 client access token from taylor tutorial. My web app uses angular js for UI and laravel for backend , so I need to create user, when create user request is sent from angular and then create a global access token to give it in my response to angular which then in all later request I use it to authenticate requests.
actually I want to implement oauth2 authentication for my web app, but so far I've searched a lot but I couldn't find any useful step by step tutorial for it.
anyone can help me out?
FYI: I'm using laravel 5.3 with passport enabled and angular js 1.5 for frontend.
Use JWT token based authentication here you can learn about jwt https://jwt.io/
I've solved this.
I've Customized laravel auth for login and register and created a method which will send a request to the server to create an access token for registering user or log in.
I've set up passport and test it as taylor did in his toturial.
then in AuthenticatesUsers.php I've changed sendloginResponse method response like :
protected function sendLoginResponse(Request $request)
{
isset($request->token) ? $token = $request->token : $token = null;//Check if login request contain token
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
? $this->StatusCode($token,$this->credentials($request),$status=false) : $this->StatusCode($token,$this->credentials($request),$status=true);
}
And I have added this method to request access token and send it as json response :
public function StatusCode($token,$user,$status){
if( $token != null && $token != ''){
return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
}
function GetToken($userobject)
{
$http = new Client;
$response = $http->post('http://localhost/iranAd/public/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '1',
'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
'username' => $userobject['email'],
'password' => $userobject['password'],
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
function RefreshToken($token,$userobject)
{
$http = new Client;
$response = $http->post('http://localhost/iranAd/public/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'refresh_token',
'client_id' => '1',
'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
'username' => $userobject['email'],
'password' => $userobject['password'],
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
}
Same Procedure for register users.
The purpose of this post is not to answer(as already answered) but to give more info to other readers who eventually need more info on topic.
This is very helpfull tutorial just on this issue Implementing Vue.js 2.0 and Laravel 5.3 with CORS problem solution
Check this one and 2 next clips.
Some of this you can find in shorter form here here

Resources