I am trying to set up Laravel Sanctum out of the box. I have barely changed a thing from the fresh install.
What I have done:
-Created a user and generated a token for them:
$token = Auth::user()->createToken('TestToken');
This works the token show up in the data base as expected.
-Added routes to my api.php
Route::get('testAPI', function () {
return 'API CONNECTED';
});
Route::middleware('auth:sanctum')->get('/testAuth', function () {
return 'AUTHENTICATED';
});
Using postman the testAPI route works.
However the calling the testAuth route returns what appears to be a blank Laravel view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title inertia>Laravel</title>
...blah blah....
Note: the page return is NOT the Laravel error page:
<!doctype html>
<html class="theme-light">
<!--
ParseError: syntax error, unexpected 'Route'
...blah blah for reference...
The page returned remains unchanged regardless of adding the bearer token to the header.
What am I missing, any help appreciated :)
UPDATE: as per #ceejayoz comment I have added Accept: application/json to my headers. Now I am receiving a reponse of:
{
"message": "Unauthenticated."
}
Additionally, I have tried adding Referer: 127.0.0.1:8000,this still results in Unauthenticated
For the authentication header in postman, please follow this screenshot.
And If need more information about how to setup laravel sanctum, please follow https://laravel.com/docs/9.x/sanctum laravel docs. There can be nothing better than Laravel docs for setting up Laravel sanctum
Related
I am currently using laravel 5.8 and pusher 3.0.3 and I am new to these new tech. I have created a simple chatroom but failed to listen to presence channel using pusher. I previously tried Echo but I can't find a way to debug it.
Here is pusher:subscription_error from the console:
Pusher: JSON returned from webapp was invalid, yet status code was 200. Data was: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
I have already added this line to my BroadcastServiceProvider.php
Broadcast::routes(['middleware' => ['auth:api']]);
require base_path('routes/channels.php');
I have already receive events from pusher debugger with public channel so I think I have set my credentials correctly.
This is the buttom part of my bootstrap.js.
const CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var pusher = new Pusher('61540f91921896045e25', {
cluster: "ap1",
forceTLS: true,
//authEndpoint: 'authchatuser'
authEndpoint: '/broadcasting/auth',
auth: {
headers: {
'X-CSRF-Token': CSRF_TOKEN
}
}
});
var channel = pusher.subscribe('presence-chatroom');
//var channel = pusher.subscribe('chatroom');
channel.bind('MessagePosted', function(data) {
console.loga(data);
});
channel.bind('pusher:subscription_error', function(data) {
console.log("Pusher: " + data);
});
From the network tab, I couldn't see request to my pusher authEndpoint broadcasting/auth, but instead I see GET request to my homepage which responded with 200 which I think is the reason why I receive html instead of json.
Please help me with this or do you have idea to bypass the endpoint and send json data for authentication (correct data expected by pusher) instead from my web.php? Thank you.
You should not need to bypass the endpoint, but instead you should amend your endpoint to return the correct data.
Your authentication endpoint should return a JSON body along with a HTTP code. The documentation states:
Successful responses from an authentication endpoint should carry a
200 OK HTTP status and a body of the form
{ "auth": $AUTHORIZATION_STRING }
This aligns with the error you are receiving which indicates that JSON is expected but HTML is received.
Laravel 5.6
Vue 2.5.7
Google Chrome
Hi, I am trying to understand this CORS issue, i'm still trying to find a way to consume this list: https://api.coinmarketcap.com/v2/listings/, and I receive the following error:
(index):1 Failed to load https://api.coinmarketcap.com/v2/listings/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://tours.mine' is therefore not allowed access.
yet if I goto this address: https://jsonplaceholder.typicode.com/posts/ everything works fine.
After using this Moesif Chrome CORS extension, and thus disabling CORS for chrome, I received a new error:
Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response. received only on this address: https://api.coinmarketcap.com/v2/listings/
http://tours.mine - is a local name I set in httpd/vhosts.conf.
I've tried BarryVdh cors lib, I also created my own CORS middleware, nada.
Flow:
in web.php routes:
Route::get('/', function () {
return view('welcome');
});
in welcome.blade I pass the csrf in both meta:
<meta name="csrf-token" content="{{ csrf_token() }}">
and script:
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
My Vue instance:
<div class="container" id="app">
<coin-add-component></coin-add-component>
</div>
and in my component I have the following hook:
mounted(){
this.axios.get('https://api.coinmarketcap.com/v2/listings/')
.then(response => {
console.log(response.data);
})
.catch(e => {
this.errors.push(e)
})
}
Your help is appreciated,
Bud
The url you are trying to consume can't be used in crossdomain with javascript because it doesn't provide a response header of type "Access-Control-Allow-Origin".
In this case, if you have no control on the API server you are forced to use other unconventional ways because all modern browsers will block any requests to that site if the domain doesn't match with yours.
You have 2 alternative to solve this problem:
Use a proxy with your same domain of yours to redirect all calls to that server
Make ajax calls to your server and then make your server communicate directly with the api server using for example curl
if you are using this(https://github.com/barryvdh/laravel-cors) make sure you turn off csrf token in your mid
i'm trying to make some requests using axios and the last Laravel version 5.5
after configure the X-CSRF fields and all
my code is simple :
axios.post('/post-contact',{name:'Kamal Abounaim'})
.then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error.response.data)
})
but i get this error : 419 (unknown status)
what the problem supposed to be
Thanks for answering
This is happening because of the csrf-token. Just add meta tag with the csrf-token in the <head> and add that token to axios header like so.
// in the <head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
// For adding the token to axios header (add this only one time).
var token = document.head.querySelector('meta[name="csrf-token"]');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
// send contact form data.
axios.post('/post-contact',{name:'Kamal Abounaim'
}).then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(error.response.data)
});
</script>
A 419 error seems to be Authentification Timeout. Your code looks fine to me, so it seems the error is with the post-contact endpoint? Try testing that endpoint alone, in a tool like postman.
Muddling through some Angular2 tutorials and trying to get a post request to work in Laravel 5.2 I have added this meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
but I'm not sure how to pass that in the headers section or honestly if that is where it should go.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '???????' });
Update: So I added a function to pull the csrf-token from the meta tag but still have not found a way to get it passed to the Laravel post request.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
Thanks
This is what I did. Not sure if it is the best way but it worked.
In the main Laravel template I added this meta tag.
<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
In the Angular2 whatever.service.ts I added a get token function.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
In the same service I added this to the post method.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': this.getToken()});
Laravel now accepts the post without the 500 Token Mismatch Error
Please chime in if there is a better solution!!
This should be the same "problem" as with <title>{{ title() }}</title>: There's no component. This means: Angular won't/can't do any interpolation here. For the title tag the angular team provides an injectable Title service. For meta tags you've got to roll your own solution.
Have a look here: https://wijmo.com/blog/how-to-improve-seo-in-angularjs-applications/
They use document.querySelector to access the meta element and then setAttribute to manipulate its contents.
There seems to be a problem if you use the SDK login function to login while the user is connected to another network. All the API calls fail and there seems to be no way to get back to the home network to authenticate.
Here is the code required to test this problem:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Yammer Login</title>
<script type="text/javascript" data-app-id="{INSERT APP ID}" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
</head>
<body>
<div id="Envelope">
<div><span id="yammer-login"></span></div>
<div><input type="button" onclick="getUserInfo()" value="Get User Info"></div>
<script>
yam.connect.loginButton('#yammer-login',
function (resp) {
console.log(resp);
});
function getUserInfo() {
yam.platform.request({
url: 'users/current.json',
method: "GET",
success: function (r) { console.log("GOT RESPONSE"); console.log(r); },
error: function (r) { console.log(r.statusText) }
});
}
</script>
</div>
</body>
</html>
If the user is logged into their home network the login code works and you can press the button to get the users information (note javascript origins are correctly configured).
You you go into the yammer interface and select another network it not longer works.
Here is what the console output looks like:
GET https://www.yammer.com/platform/login_status.json?
client_id={Client ID} 403 (Forbidden)
platform_js_sdk.js:26 XHR finished loading: GET "https://www.yammer.com/platform/login_status.json?client_id={ClientID}".
test.php:18 Object {access_token: Object, success: true, status: "connected", authResponse: true}
api.yammer.com/api/v1/users/current.json:1 GET https://api.yammer.com/api/v1/users/current.json
test.php:1 XMLHttpRequest cannot load https://api.yammer.com/api/v1/users/current.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://webserver.com' is therefore not allowed access. The response had HTTP status code 401.
test.php:26 error
api.yammer.com/api/v1/users/current.json:1 GET https://api.yammer.com/api/v1/users/current.json
test.php:1 XMLHttpRequest cannot load https://api.yammer.com/api/v1/users/current.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://webserver.com' is therefore not allowed access. The response had HTTP status code 401.
test.php:26 error
It appears that the login token that is being uses belongs to the other network and therefore access is restricted.
Based on Yammer REST API: How to get access tokens for external networks?
you need to apply to deploy to the Global App Directory. Specify by e-mail to the Biz Dev rep that your app requires Global Access (even without being published in the App Directory). This resolves the issue.
see slide 5 of http://about.yammer.com/assets/yammer-apps-next-steps.ppt