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

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)

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
);

Axios post form data with user id of Logged in user

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.

Login Wordpress user automatically on REST API call

I have a react application and currently the user authentication done with Wordpress. So I'm using JWT_AUTH! plugin to manage user login functionality.
So now the requirement has changed and the users should be able to login to both React and the Wordpress websites with one single login attempt. This means if the user login to the React application, he should automatically log in to his Wordpress application as well. Also if the user login on Wordpress application he should automatically log into his react application as well.
I have created a custom REST API endpoint to do this requirement. But it's not working as expected. This endpoint is working when I using this API link with a browser. That because it doesn't have the ability to store cookies with the REST API call.
I also tried to generate auth cookies with the rest API call but it gave me the "500" error.
add_action( 'rest_api_init', function () {
register_rest_route( 'user/v1', '/api-login-check', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'rest_api_login_user',
'schema' => array(
'type' => 'array'
)
));
});
function rest_api_login_user($object, $request = null) {
$response = array();
$parameters = $request->get_json_params();
$creds = array();
$creds['user_login'] = $object['username'];
$creds['user_password'] = $object['password'];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ($user) {
$response['code'] = 200;
$response['message'] = __("User logged in", "wp-rest-user");
return new WP_REST_Response($response, 123);
}else{
$response['code'] = 403;
$response['message'] = __("User not logged in", "wp-rest-user");
}
}
Is there any easy way to do this? Also if there a way to redirect user to different url from a rest api call, that also fine.

How do I manage an access token, when storing in local storage is not an option?

I have a ReactJS app running in browser, which needs access to my backend laravel-passport API server. So, I am in control of all code on both client and server side, and can change it as I please.
In my react app, the user logs in with their username and password, and if this is successful, the app recieves a personal access token which grants access to the users data. If I store this token in local storage, the app can now access this users data by appending the token to outgoing requests.
But I do not want to save the access token in local storage, since this is not secure. How do I do this?
Here is what I have tried:
In the laravel passport documentation, there is a guide on how to automatically store the access token in a cookie. I believe this requires the app to be on the same origin, but I cannot get this to work. When testing locally, I run the app on localhost:4000, but the API is run on my-app.localhost. Could this be a reason why laravel passport does not make a cookie with the token, although they technically both have origin localhost?
OAuth has a page on where to store tokens. I tried the three options for "If backend is present", but they seem to focus on how the authorization flow rather than how to specifically store the token.
Here's the relevant parts of my code (of course, feel free to ask for more if needed):
From my react app:
const tokenData = await axios.post(this.props.backendUrl + '/api/loginToken', { email: 'myEmail', password: 'myPassword' })
console.log('token data: ', tokenData)
const personalAccessToken = tokenData.data.success.token;
var config = {
headers: {
'Authorization': "Bearer " + personalAccessToken
};
const user = await axios.get(this.props.backendUrl + '/api/user', config);
From the controller class ApiController:
public function loginToken()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
and the loginToken function is called from the /api/loginToken route.
Expected and actual results:
Ideally, I would love to have the token saved in a cookie like in the passport documentation, so I don't even have to attach the token to outgoing requests from the react app, but I'm not sure that this is even possible. Perhaps with third party cookies?
Else, I'd just like to find some way to store the token securely (for example in a cookie?), and then append it to outgoing calls from the react app.

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