Laravel sanctum SPA - This set-cookie domain attribute was invalid with regards to the current host url - laravel-sanctum

I have a VueJS app and a Laravel API in separated projects.
I have some issues to auth with laravel sanctum.
My VueJs is on localhost:8080 and my API on localhost:8000
When i try to set cookie, i have a "This set-cookie domain attribute was invalid with regards to the current host url" issue
I think that laravel cant set cookie, when i try to auth he returned a 419 error status which mean token mismatch.
My config/cors.php
'paths' => [
'api/*',
'sanctum/csrf-cookie',
'login',
'logout'
],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
I follow the laravel documentation.
Add theses lines to my app/Http/Kernel.php
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
I activated axios credentials in my vue app
axios.defaults.withCredentials = true;
I set my SESSION_DOMAIN=localhost:8080.
In my VueJS login component :
axios
.get('/sanctum/csrf-cookie')
.then(response => {
axios.post('/login', {
email : 'alexandria96#example.com',
password : 'password'
}).then(response => {
console.log('User signed in!');
}).catch(error => console.log(error)); // credentials didn't match
});
enter image description here
The request for csrf-cookie
enter image description here
The request for login
enter image description here

Before logging in you have to check that cookie are setted. Your cookie is not set that's why you have 419 error.
Try to take away ports from configs.
Try
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost
And now check cookies. For me works.

Related

How to fix the 'invalid_grant' error when using Google Photos API

I'm trying to use the Google Photos API (quite a newbie on this). I've managed to go through the authentication/consent process. I stored the authorization code that was returned by Google. On a later moment, I'm trying to use this authorization code to use the Google Photos API. Below a code snippet.
// $clientId and $clientSecret are read from my .json file
// $state was randomly generated, used in the registration process and stored to/read from the database
// $code was stored to the database at the end of te registration process and read from the database to pass in subjoined call
// $redirectUrl and $scope are hard coded for now
$oauth = new OAuth2( [
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'state' => $state,
'redirectUri' => $redirectUrl,
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'scope' => $scope,
] );
$oauth->setCode( $code );
$credentials = new UserRefreshCredentials(
$this->getScope(),
[
'client_id' => $oauth->getClientId(),
'client_secret' => $oauth->getClientSecret(),
'refresh_token' => $oauth->getRefreshToken()
]
);
$client = new PhotosLibraryClient( [ 'credentials' => $credentials ] );
For the refresh_token, I've tried both $oauth->fetchToken()['access_token'] as well as $oauth->getRefreshToken().
Unfortunately, I get an exception:
guzzlehttp/guzzle/src/Exception/RequestException.php # 113 : Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `400 Bad Request` response: { "error": "invalid_grant", "error_description": "Bad Request" }
Anyone any idea what could be wrong here?

How to fix getFederationToken returns 403 not authorized error after upgrading from SDK version 1 to 3

We have existing code that uses AWS PHP SDK version 1 AmazonSTS()->get_federation_token(). After upgrading to SDK version 3, the same call using the same credentials, resource and policy returns a 403 not authorized error.
Version and region appear to be the same. The policy json is the same. The user credentials used to make the call are the same (and if I switch back to the SDK v1 they still work). I have the debug option set but it doesn't appear to provide any additional information as to why the same user it not authorized to perform the same function getFederationToken on the same federated user.
Old code that works:
$client = new AmazonSTS();
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
// Fetch the session credentials.
$response = $client->get_federation_token('User1',array(
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS
));
New code that returns 403 error:
$client = new Aws\Sts\StsClient([
'region' => 'us-east-1',
'version' => '2011-06-15',
]);
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
try {
$response = $client->getFederationToken([
'Name' => 'User1',
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS,
]);
} catch (Exception $e) {
var_dump($e);
die();
}
The first example returns temporary credentials for the federated user User1.
The second example returns 403 forbidden error (I'm hiding the actual account id):
<Error>
<Type>Sender</Type>
<Code>AccessDenied</Code>
<Message>User: arn:aws:iam::[account id]:user/portal is not authorized to perform: sts:GetFederationToken on resource: arn:aws:sts::[account id]:federated-user/User1</Message>
</Error>
Turns out I was looking at the wrong credentials. I found the correct credentials hard-coded in the script :(

Invoke Rest API using Oauth 2.0 token in logstash http output plugin

I am trying to publish log events to my rest API using logstash http output plugin. It works if there is no authorization or I enable the basic authentication But my requirement is to invoke the API using Oauth 2.0 access tokens. When I specify the Authorization header with access token I am getting 401 error. From SOAPUI I have tested token is working fine. Below are the logstash configs.
output {
if [type] == "error" {
if "loglevelerror" in [tags] {
#*******************************************************************
# Sending Messages to EventAPI
#*******************************************************************
http {
url => "http://serverip:8281/events"
headers => {
"Authorization" => "Bearer c505e8f7-ecb3-346f-8216-f906965edc17"
"RequestSource" => "agent"
"Accept" => "application/json"
}
connect_timeout => 60
socket_timeout => 60
http_method => "post"
format => "json"
mapping => [my mappings]
}
}
}
}
Any help would be a great favour.

Google_AuthException [ 400 ]: Error fetching OAuth2 access token, message: 'invalid_grant'

The problem arises when I get the code and makes a request for a token. For authorization using code that works fine on other projects. I check Credentials in developer console and my config file. Attempts to connect the authorization from other sites and other accounts yielded nothing. I checked redirects, headers, but found nothing.
$request = Google_Client::$io->makeRequest(new Google_HttpRequest('https://accounts.google.com/o/oauth2/token', 'POST', array(), array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
This request return "Error fetching OAuth2 access token, message: 'invalid_grant'"

Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST

I am working with YouTube APIs for my college project, and I keep getting an error. Here I send them to the authorisation page to log in, when they allow access it sends the $_GET['code'] string back. Then I send this along with some other data and it should send back a JSON object. Instead I am just getting
Warning: file_get_contents(https://accounts.google.com/o/oauth2/token)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 400 Bad Request in http://www.example.net/callback.php on line 27
I have replaced my domain with example.net just for security
urlencode($_GET['code']),
'client_id' => urlencode('111522767640.apps.googleusercontent.com '),
'client_secret' => urlencode('secret'),
'redirect_uri' => urlencode('http://example.net/callback.php'),
'grant_type' => urlencode('authorization_code')
)
);
$params =
array('http' =>
array(
'method' => 'POST /o/oauth2/token HTTP/1.1',
'header' => 'Host: accounts.google.com\r\n'.
'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($params);
$result = file_get_contents('https://accounts.google.com/o/oauth2/token', false,$context);
var_dump($_SESSION);
var_dump($result);
}
else //If code isnt set, user must have come here erroniously or has denied access to this program
{
//header( 'Location: www.example.net/error.php' ) ;
}
?>
file_get_contents is going to make a GET request to the url specified, but oauth2/token needs a POST request.
See reference Google OAuth2, PHP HTTP.
if you are using oauth2, goto libraries/oauth2/provider.php and uncomment the code line 182 shows
$ci = get_instance();
$ci->load->spark('curl/1.2.1');
$ci->curl
->create($url)
->post($params, array('failonerror' => false));
$response = $ci->curl->execute();
Here's how to do the Google oAuth properly:
$config = (object) array(
'CLIENT_ID' => 'AAAAA',
'CLIENT_SECRET' => 'BBBBB',
'REFRESH_TOKEN' => 'CCCCC',
);
$sJSON = file_get_contents('https://www.googleapis.com/oauth2/v4/token',FALSE,
stream_context_create(array('http'=>array(
'ignore_errors' => TRUE, // see errors in response instead of empty on error
'method' => 'POST',
'header' => array(
'Content-Type: application/x-www-form-urlencoded'
),
'content' => http_build_query(array(
'grant_type' => 'refresh_token',
'client_id' => $config->CLIENT_ID,
'client_secret' => $config->CLIENT_SECRET,
'refresh_token' => $config->REFRESH_TOKEN
))
)))
);
You can then use json_decode() to parse $sJSON into an object and then retrieve the access_token property.
For those who are wondering how to get the CLIENT_ID, CLIENT_SECRET, and REFRESH_TOKEN, watch this video. It's not easy. In my case, I needed to do this for Google Adwords API. So, I had to get my Developer Token and Login Customer ID from https://ads.google.com/home/tools/manager-accounts. Then, I had to go to https://console.developers.google.com/apis/credentials with this guide to generate a Client ID and Client Secret. Then, I followed this guide to learn how to get my Refresh Token.

Resources