How to get around auth level when testing API on laravel project? - javascript

I am using the basic Auth from laravel that you get from running the following command.
php artisan make:auth
I have an API written so that the backend on the server can update/create services and statuses. The issue i'm running into is that the Admin also has a UI on the web app and can create a service, or update its status manually. Therefore, I have an Auth level on the methods where you have to be logged in to use them.
Now when I call the method in postman it redirects me to the login page, I was wondering if there was a way around this Auth level strictly for an API?
I was told of a way to do pre-request scripts directly in postman but i'm fairly lost when it comes to the whole java script part of that and feel like there is an easier way to do it. I also already tried to do 'basic auth' with the username and password, it didnt seem to work though.
Thank you for the help in advance!
Edit: Here is the screenshot from my header.

I am presuming if you have the API in place you have an api_token set for the specific user. You can use that inside Postman in one of two ways.
You will goto the Headers tab and add:
Key: Authorization
Value: Bearer API_TOKEN_VALUE
Edited: Added the screenshot of postman
You can amend the url for the request and add the token:
url_to_api_endpoint?api_token=API_TOKEN_VALUE
On the api routes if you have ->middleware('auth:api') Laravel will read the authorization token from the header or using the query parameter and check it to the database value.
Adding the api_token to the user table
If you don't have an api_token field in your user table then add one. It is not the same as remember_token, they are different. So add to your user migration the following:
$table->string('api_token', 60)->unique();
You will need to update the users api_token using something like the following:
$user = User::find(1);
$user->update(['api_token' => str_random(60)]);
That 60 character string you will use where I put VALUE_OF_TOKEN_FROM_DB

Related

How to keep my node js endpoints safe and to be accessible only from my website?

I have endpoints coded in Nodejs... I use the following codes to keep them safe...
const corsOption = {
origin: ['https://www.mywebsite.com'],
};
app.use(cors(corsOption));
if (host !== "myendpoint.com") {
return res.status(403).json({ message: "forbidden access" });
}
will these keep my endpoints safe... or do I have to do anything more for my endpoints to keep them safe... I don't want bots or anyone else to use it... I know that they are public but I want to restrict access... pls, any help or suggestion ???
thank you
To be sure you can control who can access your endpoint, you can setup a token authentication.
When you send a request to your endpoint, the header should include:
Authorization: Token {your token}
And in your endpoint, you can check if the token is authorized or not (by storing authorized token in a database). If the token is not recognized, you can send back a 403 error.
If your website accesses your endpoints, this means that any browser that can display your website must also be able to access your endpoints. Requests are not made by your website, they are made by browsers visiting your website.
You must first ask how much you want to restrict access:
Restrict to individual known users to whom you send a password via mail, which they must then type into your website ("log on") before they can make any requests to your endpoints.
Restrict to users who have self-registered. Can anyone in the world then self-register, or do you demand confirmation via an email address?
Restrict to users who can log on with their Google (or Facebook, or ...) account.
Zain_Ul_Din's answer shows details of a possible implementation for the "self-registration" case. See also What's the best way to add social login (Sign in with Google) to existing email/password app and database?
you can implement user authentication and authorization in your Node js app to restrict access.
for this you can use the jsonwebtoken npm package.
Look up John Smilga's node and express projects on google for a 10hr video including 4 projects. One of the projects introduces JSON web tokens and how to use them.I highly recommend that.
You can also use the express-rate-limit package. With this you should be able to 'limit' how many requests a user can make to your API endpoints within a set amount of time. If the requests exceed that limit then this middleware steps in and stops further access (Haven't tested it in production myself but looks good)

Safe to call WooCommerce, WordPress and CoCart endpoints in frontend? I need your opinion

Question
I got a question about security. I am building a mobile webshop in Flutter. Is it bad to make those API calls in the frontend? Should I make a separate backend for it in Node for example?
I have also read that you can 'create' your own endpoints in WordPress with PHP. What about that? Does that make it any safer or not?
What endpoints do I use?
There is an existing WooCommerce API to retrieve products, get categories, and create orders on the WooCommerce API. On the CoCart API, you can retrieve the cart, add to the cart, delete the cart, etc...
For the Mollie payment APIs, I think it is better to make a backend.
My take on it
I think it is fine to call those endpoints in the front end. I have seen Flutter packages for WooCommerce to call those endpoints. Yes, I do send the basic auth in the headers... so I am not sure how 'dangerous' that is.
But on the other side. What can the 'hacker' do? They can see all the products, that is fine I guess. I am not sure if they can create orders... They cannot steal money at least :)
Reference code
For reference, here is a piece of code when calling an endpoint:
Future<Product> getProductById(int productId) async {
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
var response = await http.get(
Uri.parse(
'https://websitename/wp-json/wc/v3/products/${productId}'),
headers: <String, String>{'Authorization': basicAuth});
if (response.statusCode == 200) {
return Product.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed');
}
}
Let me know your opinion!
When talking about security main question is what goes over the network request. If your username & password from code above is something to keep secret, that can't be on client side.
If you sent code to user, user got it and can check what's happening while tracing network requests.
You can always skip the UI, debug network request and take all the details that were sent over that request and send those requests with cURL or anything else. Yet client must authenticate somehow, and that's a wide topic from "unlisted" URLs where you just need to have exact "random id" to get to the resource (e.g. youtube's or many file sharing services use that as "unlisted" link, which means this won't be in search results but if you have exact link, you will get into the resource) to oAuth2, which you can learn more about here and
you could check this post too which covers several methods of token-based authentication.

How to use Chrome extension get Laravel passport token?

I'm working on using Chrome extension access Laravel passport API. Currently, the Laravel passport API is setup and working. I tried to use chrome.identity.launchWebAuthFlow to get passport token but not working. There is an example provided by Google, it is different from my use case.
I have two questions:
According to the Laravel document, the first step is request an authorization code, the API end point is /oauth/authorize. What the redirect_uri should be since it is a chrome extension but not a website?
After the user approve the request, I'm using chrome.identity.launchWebAuthFlow to get the access token from Passport. In laravel it is a POST request, the end point is /oauth/token. But I tried chrome.identity.launchWebAuthFlow, it is a GET request.
I can make this whole process working using PHP but not Chrome Extension. Any suggestions?
As per the launchWebAuthFlow docs:
When the provider redirects to a URL matching the pattern https://app-id.chromiumapp.org/*, the window will close, and the final redirect URL will be passed to the callback function.
As an example, you could use the following code:
let redirectUrl = chrome.identity.getRedirectURL('redirect');
chrome.identity.launchWebAuthFlow({
url: `https://my.app.domain.com/oauth/authorize?client_id=xxx&response_type=code&scope=&redirect_uri=${redirectUrl}`
}, (redirectUrl) => {
console.log(redirectUrl) // Redirect URL with oauth query params added
})

AngularJS $http.get does not return expected data from API

I am attempting to create a mobile phone application with a javascript / AngularJS frontend that communicats with a node js / express js backend.
I believe that I have properly enabled cors but am not completely certain that it has been done in the correct manner. None of the frontend files are hosted on a server (not even a local one). The node js server is hosted online as well as a mongo db server that it interacts with.
So far I am able to make POST's to my API that create a new user and reflect this in the database. I also have a login that POST's to an authentication function which returns a JSON Web Token (JWT). From here I should be able to put the JWT in the header of requests with the key "Authorization" to get access to the other parts of the API (eg: GET /currentUser).
Attempting to GET /currentUser when the JWT is in the header with postman returns all of the expected data. When I attempt to perform the same GET from my frontend (with JWT in header), I get the following OPTIONS response via firebug: "Reload the page to get source for: MyHostedApi/api/users"
I'm wondering if this is some kind of cors issue, incorrectly set authorization header, bad formatting of the $http.get, etc. Any help is greatly appreciated! I'd be glad to provide any parts of the source that are relevant.
This is what my GET looks like:
$http.get("MyHostedApi/api/users/currentUser")
.success(function(response) {
$scope.userData = response.data.firstName;
});

Twitter JS API, update status

I'm at a total loss here. I believe I'm right in thinking there is no longer any JS API for twitter which just sucks hugely.
However I realise looking at this I could just use ajax and react to the responses from this:
https://dev.twitter.com/rest/reference/post/statuses/update
OAuth Signature Generator
Example Request POST
https://api.twitter.com/1.1/statuses/update.json?status=Maybe%20he%27ll%20finally%20find%20his%20keys.%20%23peterfalk
However when I post to that url I get the following:
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
Bad Authentication data -> this is very self explanatory: Your Authentication is Bad; in other word, you are not authorized to use that API method.
Since you use POST method, make sure you set your APP access level to Read & Write.
Sign in to apps.twitter.com, and in the Applications Management page for your app, click the Permissions tab. There you can change your access level.
For further reading, please see this answer.

Categories

Resources