Laravel websocket in subdirectory - laravel-5

please can you help me.
My scheme of files is:
var/www/turnerosac --> files base projects
/var/www/html/turnerosac --> files public
When executing the command:
/usr/bin/php /var/www/turnerosac/artisan websocket:serve
Throw the following message in the console
Starting the WebSocket server on port 6001...
New connection opened for app key e992c96bf63f43766490.
Connection id 154192426.353203179 sending message {"event":"pusher:connection_established","data":"{"socket_id":"154192426.353203179","activity_timeout":30}"}
My bootstrap.js
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'e992c96bf63f43766490',
cluster: 'us2',
wsHost: window.location.hostname,
wsPort: 6001
// disableStats: true,
});
In browser

Related

Is there a way to add a custom query string to the pusher (laravel-echo) options list?

I'm using Laravel WebSocket + Laravel Echo.
My Websocket URL is
ws://mydomen.loc/socket/app/my_key?protocol=7&client=js&version=7.0.6&flash=false
How can I add &param=value to the
new Echo({
broadcaster: 'pusher',
...
});
for get ws://mydomen.loc/socket/app/my_key?protocol=7&client=js&version=7.0.6&flash=false&param=value

Setting redirect when accessing Cognito via sk-auth

I have built a Svelte application using SvelteKit that uses Cognito for authentication. I used the following site: Cognito authentication for your SvelteKit app guide me in setting this up. The app and connection to Cognito works well when running in local development via npm run dev, however, when running in production on an EC2 server via npm run build and pm2 start /build/index.js it sets the redirect_uri portion of the Cognito URI to http://localhost:3000. I can't figure out how to get it to set the redirect to my actual domain.
Here are some relevant code snippets on how it is currently set up on EC2:
/etc/nginx/sites-available/domain.conf
server {
server_name example.com;
location / {
root /var/www/html/build;
proxy_pass http://localhost:3000;
}
listen [::]:443 ssl ipv6only=on;
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
svelte.config.js
import node from '#sveltejs/adapter-node';
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
target: '#svelte',
adapter: node({
out: 'build',
precompress: false,
env: {
host: 'example.com',
port: '443'
}
})
}
};
export default config;
/src/lib/auth.js
import { SvelteKitAuth, Providers } from 'sk-auth';
const DOMAIN = 'myapi.auth.us-east-1.amazoncognito.com';
const config = {
accessTokenUrl: `https://${DOMAIN}/oauth2/token`,
profileUrl: `https://${DOMAIN}/oauth2/userInfo`,
authorizationUrl: `https://${DOMAIN}/oauth2/authorize`,
redirect: 'https://example.com',
clientId: myAWSclientID,
clientSecret: myAWSclientSecret,
scope: ['openid', 'email'],
id: 'cognito',
contentType: 'application/x-www-form-urlencoded'
};
const oauthProvider = new Providers.OAuth2Provider(config);
export const appAuth = new SvelteKitAuth({
providers: [oauthProvider]
});
Expected URL when going to Cognito
https://myapi.auth.us-east-1.amazoncognito.com/login?state=cmVkaXJlY3Q9Lw%3D%3D&nonce=699&response_type=code&client_id=myAWSclientID&scope=openid+email&redirect_uri=https%3A%2F%2Fexample.com%2Fapi%2Fauth%2Fcallback%2Fcognito%2F
Actual URL when going to Cognito
https://myapi.auth.us-east-1.amazoncognito.com/login?state=cmVkaXJlY3Q9Lw%3D%3D&nonce=699&response_type=code&client_id=myAWSclientID&scope=openid+email&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fcallback%2Fcognito%2F
As you can see, it is attempting to set the redirect_uri to http://localhost:3000 instead of the expected https://example.com. I'm pretty sure that there is some setting somewhere to allow it to set the correct redirect_uri when going to Cognito - any ideas or suggestions would be appreciated!
From what I can tell looking at the sk-auth module source code, redirect_uri doesn't appear to be a valid config option. Try setting the host config option in the global SkAuth constructor instead:
const config = {
accessTokenUrl: `https://${DOMAIN}/oauth2/token`,
profileUrl: `https://${DOMAIN}/oauth2/userInfo`,
authorizationUrl: `https://${DOMAIN}/oauth2/authorize`,
// redirect_uri: 'https://example.com',
clientId: myAWSclientID,
clientSecret: myAWSclientSecret,
scope: ['openid', 'email'],
id: 'cognito',
contentType: 'application/x-www-form-urlencoded'
};
.
.
export const appAuth = new SvelteKitAuth({
providers: [oauthProvider],
host: 'https://example.com',
});
After further browsing the source, you can also set the redirect option provided by the AuthCallbacks interface on the provider configuration:
const config = {
accessTokenUrl: `https://${DOMAIN}/oauth2/token`,
profileUrl: `https://${DOMAIN}/oauth2/userInfo`,
authorizationUrl: `https://${DOMAIN}/oauth2/authorize`,
// redirect_uri: 'https://example.com',
redirect: 'https://example.com',
clientId: myAWSclientID,
clientSecret: myAWSclientSecret,
scope: ['openid', 'email'],
id: 'cognito',
contentType: 'application/x-www-form-urlencoded'
};
which, incidentally, is what the author uses in the tutorial you referred to.

Laravel pusher, /broadcasting/auth:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)

I clear the cookies, then I log into the account and get the token, as soon as I enter any page where there are sockets I get errors:
[2020-08-10 17:50:43] local.ERROR: The resource owner or authorization
server denied the request. {"exception":"[object]
(League\OAuth2\Server\Exception\OAuthServerException(code: 9): The
resource owner or authorization server denied the request. at
C:\laragon\www\delivery\vendor\league\oauth2-server\src\Exception\OAuthServerException.php:243)
[stacktrace]
#0 C:\laragon\www\delivery\vendor\league\oauth2-server\src\AuthorizationValidators\BearerTokenValidator.php(88):
League\OAuth2\Server\Exception\OAuthServerException::accessDenied('The
JWT string ...', NULL, Object(InvalidArgumentException))
[previous exception] [object] (InvalidArgumentException(code: 0): The
JWT string must have two dots at
local.ERROR: Route [login] not defined. {"exception":"[object]
(Symfony\Component\Routing\Exception\RouteNotFoundException(code:
0): Route [login] not defined. at
C:\laragon\www\delivery\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:420)
[stacktrace]
If I reload the page, the errors disappear forever. These errors appear only the first time when you get to a page where sockets are used, I use vue js on the frontend. For authentication I am using laravel passport.
local settings of my pusher
indow.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
authEndpoint: '/broadcasting/auth',
auth:{
headers:{
Authorization:'Bearer ' + Cookies.get('access_token'),
},
},
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
wsHost: window.location.hostname,
wsPort: 6001,
disableStats: true,
encrypted:false,
forceTLS: false,
enabledTransports: ['ws', 'wss'],
});
The production has a secure connection, the error exists.
For authentication I use laravel passport
The error message reads: Route [login] not defined
... this means that you lack the default Auth::routes().
Run php artisan ui vue --auth for a fresh app.

What is Laravel websocket's url?

I'm using Laravel Websockets as my websocket server and I was wondering what is its URL? I've set the port to 6001 and the host is localhost but when I go to http://127.0.0.1:6001 or ws://127.0.0.1:6001, I get a 404 response. Any idea to get the good URL?
Thank you
You can't really go to ws port through browser. In that case, you should bootstrap a quick front-end application that initialize the Laravel Echo with configuration to your web socket server.
import Echo from "laravel-echo";
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
wsHost: window.location.hostname,
forceTLS: false,
wsPort: 6001,
disableStats: true,
authEndpoint: "http://localhost:8000/broadcasting/auth",
key: "123321",
enabledTransports: ["wss", "ws"],
auth: {
headers: {
Authorization: `Bearer `,
},
},
});
window.Echo.connector.pusher.connection.bind("connected", () => {
console.log("connected");
});
With that setup, you could load your front-end and inspect the console and you should see the connected message.
You can also go network tab in inspect and sort for WS network only, you'll see a messages being sent in real time.
If you open resources/js/boostrap.js.
You can actually change the value of the laravel-echo host and port.
if you're using socket.io
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'localhost:3001'
});
reference:
https://github.com/laravel/laravel/blob/master/resources/js/bootstrap.js#L23

Laravel broadcasting / WebSockets: Only connect users who are logged in

I set up Laravel WebSockets. My site only provides live / WebSockets functionality for users who are logged in. So there is no need to connect guests to my WebSockets server too. How can I prevent guests from connecting?
I advice you use SocketIO, Laravel Echo, and Laravel Echo Server.
Get a user access token, store it in a cookie or web storage (localStorage or sessionStorage) and inject it while instantiating Laravel echo:
let Echo = require('laravel-echo')
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':3434'
auth: {
headers: {
Authorization: 'Bearer ' + AUTH_TOKEN,
},
},
});
Here are the links for your needs:
https://laravel.com/docs/5.8/broadcasting#driver-prerequisites
https://github.com/tlaverdure/laravel-echo-server

Resources