Is there is any way to identify where the API request comes from - laravel

I'm working on the Flutter app which is using APIs to get the data from the server. The flutter app is public and anyone can use without login to the application. And all working fine.
My question: is there is any way to identify where the API request comes from. Because anyone can use this API to get data and this may lead flooding the server.
If it is possible to find out from where the request is coming from, then I can process the request that is ONLY from my Flutter application.
Is it possible?

Use https as protocol and add an api key and client secret to your app.
Then protect your api with e.g. http basic auth or OAuth.
https://laravel.com/docs/7.x/authentication#stateless-http-basic-authentication
https://laravel.com/docs/7.x/passport

when the first request comes in to the server, issue a token, for example
(psuedo code)
//here stringContainingData can be a json string having details about the client and the connection
token = MyHashingFunctionUsingAPassword(stringContainingData,MyStrongPassword);
after sending back the token, next api access should contain the token with every request if not reject, if the token exists, do this
stringContainingData = MyDeHashingFunction(token,MyStrongPassword)
//verify data
mappedToken = stringToMap(stringContainingData);
if(mappedToken.containsKey('keyThatShouldBePresent') //acknowledge request
else //reject request
to reject further flooding, set max requests/second from a single IP

Related

How to silently renew Id Token using AddMicrosoftIdentityWebAppAuthentication to Call Downstream API

I am trying to implement the BFF-Gateway pattern (no tokens in the browser) to be used with a React SPA. The BFF is using AddMicrosoftIdentityWebAppAuthentication to handle login and issue a cookie to the SPA. And it is using YARP to proxy api requests to a downstream api. I'm using Azure B2C. Everything works perfectly until the BFF id_token expires in 1 hour. At that point, fetching the downstream api access token via GetAccessTokenForUserAsync (which is called in a piece of middleware) fails:
var scope = _configuration["CallApi:ScopeForAccessToken"];
var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { scope });
ctx.Request.Headers.Add("Authorization", "Bearer " + accessToken);
Exception:
IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.
ResponseBody: {"error":"invalid_grant","error_description":"AADB2C90085: The service has encountered an internal error. Please reauthenticate and try again.\r\nCorrelation ID: 622d6bd6-d06e-4142-86f2-b30a7a17b3b5\r\nTimestamp: 2022-11-25 09:31:23Z\r\n"}
This is effectively the same as Call Downstream API Without The Helper Class example and this sample, except that I'm acquiring the access token in middleware, not a controller, so the downstream YARP requests contain the access token. BTW I get the same error if I do this inside a controller per this example. And I see no soluton to this in the sample.
There is a similar question here which references the sample referenced above, but for the B2C sample I see no solution to this problem.
I also found this sample and this explanation. But this uses Microsoft.Owin to configure auth, not AddMicrosoftIdentityWebAppAuthentication. This looks promising, but is a departure from most examples I see that use Microsoft.Identity.Web.
Can you please point to the correct soluton? I need call to be able to call _tokenAcquisition.GetAccessTokenForUserAsync after the id token expires without asking the user to reauthenticate and/or the SPA to having to reload.
At the moment I am handling this issue in the SPA by catching the exception from MSAL and redirecting back to the login endpoint in the BFF which initiates the challenge. This gets me a new id_token and cookie, but this is just a temp workaround as it's very disruptive to user to be redirected away from the SPA.

How to intercept an HTTP redirect response in Power Automate?

I have a Power App and Power Automate solution integrated with Docusign using their REST API's.
My issue is that I have users log into Docusign from a link which when completed and authenticated, returns an https response (authorization code) on the redirect uri. I want to be able to 'capture' the authorization code within Power Automate.
I want to avoid using custom connectors as they seem unreliable when using Oauth2 authentication and the users access token has expired. My preference is to use the HTTP REST API steps in Power Automate instead.
With a redirect to https://localhost:3000/auth/docusign/callback, I get the following https response:
https://localhost:3000/auth/docusign/callback?code=eyJ0eXAiOiJNVCIsImFsZyI6IlJTMjU2Iiwia2lkIjoiNjgxODVmZjEtNGU1MS00Y2U5LWFmMWMtNjg5ODEyMjAzMzE3In0.AQoAAAABAAYABwAAlzFclSfZSAgAACO4o5Un2UgCAOid-3Oz8jJHsDvIUG5hRR8VAAEAAAAYAAEAAAAFAAAADQAkAAAAZjA5Y2U4NDQtM2U5Yy00NjEzLTkwNzctNGY5MmFhY2NjZTc4IgAkAAAAZjA5Y2U4NDQtM2U5Yy00NjEzLTkwNzctNGY5MmFhY2NjZTc4NwBBDjKOCdhvSaNUWiI7O-21MAAAkAfAlCfZSA.zrYv2gsNFPVWHZpoO7-_5o4Ika3DxQpbNqlPUHiOvYFVL5igRnbZHh2V7OmN0bff7Tf14QF3pWaBAATozpIgzgj21m3ZjLbhY5J42eR1msXmoXjbBggibGC_FqbprVCzjSCvjbvMlwgEwda7LApdSWwr49ON9KhdN84qWD9sacJJvdi3Oi1KInImlVB_2rTpCLFhMD98PBv6b074yTqLOfwV31QT-6si8xLtk3G2vtn2gFZigXQxIA18b6tC-BM3NOILV1zwZNa1pstxxG2W8jJByUQlAux3d1GuS4vnDu_nr54mXULV0vY7txLFRiJA5w_E7Nlu2dlaOa5_DmfpNg
I want to intercept the code=eyJ0e........ in my flow.
I have tried setting up an http request and using the unique endpoint, used that as a redirect endpoint to send it to a receiving HTTP request flow. Docusign did not like the http request URL as a redirect.
I have to think this is a very simple thing to do and probably has to do with how the redirect/callback is configured in Power Automate. There maybe third party solutions that can act as a redirect intermediary which I can then GET with an API call. All ideas appreciated.

generate accessToken to retrieve data from api using passport

Is there any possible way to generate access Token so that when anyone
tries to retrieve data from the API they must pass the token as header
to get access to that
I have been searching for it but it every website is showing this->
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
There won't be any user for this purpose, When the other website will hit this api with valid header it will atomatically send all the data to that device .....
can anyone help me with this any help would be highly appreciated ....
Why dont you create a database called token and store multiple token strings.
Then, whenever, a request hits the server it checks for that token is present or not in the https header.
This way you can create multiple tokens and share it with your API partners. However, this is always public so you might want to add security features on it.
Since you dont have users, there will not be a two way handshake such that you will have to keep sending same token on all requests
So my proposal would be use of API Secret keys.
Steps:
Store api keys in database tables
Send API keys in http headder
As soon as the request hits the server check if token is present in the header
IF token is present check if the token matches database records
By the way without a user the api token is not that secured.

How to pass CSRF token with the RestTemplate

I have two Spring Boot REST applications. One of the applications calls other with Spring RestTemplate. Lets call these applications server and client app.
Server app is sending XSRF-TOKEN token as cookie, this is done for the UI part. However there's no way (None that I know of) for the server to distinguish between the request coming from browser and a request coming from the client app. So I can not selectively send the CSRF token from the server to browser only.
Is there a built in mechanism in Spring which allows RestTemplate to detect CSRF cookie/header and replay the request?
If not how can I do the same manually? Should I wait for the CSRF exception to occur and then read the cookie fro the response and replay it?
If it were to be done once then it would be OK, however to wait for the exception for every RestTemplate call doesn't seem right.
I may try to store the token once and set in from the next time, however how would it deal with the multiple server app scenario (Which I have to implement next). As CSRF token of one server app would be invalid for the other, so I won't be able to store a single token, but I would have to store a map of tokens which would have an entry for every new server app URL.
This all seems too complicated, I would rather have Spring handle it.
Any clues are appreciated.
Thanks
For now I have implemented a REST service without protection in the server app which can be called to get CSRF cookies. I had to allow session to be created always so that CSRF cookie doesn't change in one session and so that I could avoid the error Could not verify the provided CSRF token because your session was not found.
Client app calls CSRF rest service to get the cookies and then sends it with the next service call.
It seems a much to call the CSRF token service for each REST call via RestTemplate however it saves me from implementing complicated logic of storing the session. CSRF token service just delivers the cookies so it's network call doesn't take much time compared to the actual service call.
I was also thinking of using a persistent storage (SQL Database or Redis) to store the CSRF token for the server app and then let the client app directly read it from the persistent storage.
However I couldn't figure out how to associate the Session + Server app + CSRF token together to identify token needed by client. As client doesn't have the session initially, so it can't uniquely find CSRF token for it's token from the database. This method is complicated further by the fact that RestTemplate doesn't store the session for the next call.

REST API Login approach

We are building system that required login information for all pages. the application is designed to be Restful application using codeigniter as Phil Sturgeon library. This library is using API Key only to authorize api calls via sending it with every request over HTTPS connection.
Even if it using 2 way authentication or only API Key. What i am searching for a while is the following scenario:
User request the application for the first time (ex: https://www.xyz.com) then it will be redirected to the login page to check credentials
User enter the usernam/password and sent it via POST over the https
Server check if the information is valid then:
API KEY should be provided by the server to the client as a resource identified by this username (Here is the question???!!!)
How to send the API Key to the client in a secure way?
1) Could i use session-cookies and restore the API KEY in a cookie then use this API KEY on every coming request (This is violent the Stateless of the Rest and i don't sure if it securely enough).
2) Actually i don't know other options :) it's your turn if you could help
If you could give an example it would be a great help as i found and read lots of articles
:)
Since the connection is HTTPS, anything you send over the wire is secure (theoretically and provided you aren't being mitm'd). Not sure if the whole API is served over HTTPS (you didn't specify), so even though you could return the key as part of the login (while still under the umbrella of HTTPS), if the rest of the api isn't HTTPS, the key could be sniffed on the next request.
Sessions and cookies aren't typically part of a RESTful application; REST is stateless.
Something like a revolving key would be better for non-HTTPS (would work with HTTPS too). You login via HTTPS, server returns the api key, you use it on the next request, server returns new api key, you use it on the next request and so on. While it's better than a single api key over non-HTTPS, it's not perfect. If someone sniffs the response from one of the subsequent requests and you don't end up consuming that key, they can use it. This shrinks the attack vector to a non-HTTPS response from server to client since if a request from client to server is sniffed, the api key will have already been consumed by your legitimate request. However, more should be done to secure the api if you aren't serving it over HTTPS.
If it were me, I'd look into request signing + https. There's some talk of request signing here: https://stackoverflow.com/a/8567909/183254
There's also some info on digest auth at the Securing the API section of http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
A pseudo-code example js function on the client
function get_calendar(){
var key = $('#api_key').value();
$.ajax({
type: 'get',
url: '/index.php/api/calendar?key=' + key,
success: function(response){
// show calendar
// ...
// set received api key in hidden field with id api_key
$('#api_key').value(response.api_key)
}
})
}
Example controller method:
function calendar_get($api_key = ''){
if($api_key_matches){//verify incoming api key
$r = array();
$r['calendar'] = $this->some_model->get_calendar();
$r['api_key'] = $this->_generate_api_key();// generate or get api key
}
$this->response($r);
}

Resources