How to connect api via SSL, Vuejs3 - spring

I´m trying to connect from my Vue3 webpage to my API and its always showing me:
GET https://xxxxx:3000/xxxx net::ERR_SSL_PROTOCOL_ERROR
I think i need to import into vue the API-Cert, but how am i doing this?
My vue.config.js
module.exports ={
https:{
https: true
},
devServer: {
proxy: 'https://xxxx:8443/',
disableHostCheck: true,
https:true,
hot: true,
}
}
The request
async login(){
let result = await axios.get(
`https://xxx/api/login?
username=${this.username}&password=${this.password}`
)
console.warn(result)
}

Related

NextAuth getSession from subdomain not working

I am building a platform that offers different applications, the main platform is running on http://localhost and the applications will run each on a specific subdomain, at the moment I have an application running on http://sub.localhost.
I am using Nginx and Docker to host both the platform and the application, my goal would be to authenticate on http://localhost and use the session of the platform in the applications (subdomains), I have already taken a look at every single source/similar problem but could not find a solution, some of the sources I have read are the following:
https://github.com/nextauthjs/next-auth/discussions/1299
https://github.com/nextauthjs/next-auth/issues/405
https://github.com/nextauthjs/next-auth/issues/2718
At the moment this is my .env.local on the main platform:
NODE_ENV=development
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GOOGLE_AUTH_URL=...
NEXTAUTH_URL=http://localhost/
NEXTAUTH_URL_INTERNAL=http://mygames:3000/
NEXTAUTH_SECRET=...
DATABASE_URL=...
NEXT_PUBLIC_API_KEY=...
NEXT_SECRET_API_KEY=...
The following is the .env.local of the application (subdomain):
NEXTAUTH_URL=http://sub.localhost/
NEXTAUTH_URL_INTERNAL=http://mygames:3000/
NEXTAUTH_SECRET=...
DATABASE_URL=...
NEXT_PUBLIC_API_KEY=...
NEXT_SECRET_API_KEY=...
The following is my [...nextauth].js for the main platform:
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaAdapter } from '#next-auth/prisma-adapter';
import prisma from '../../../lib/prisma';
import Stripe from 'stripe';
const getDomainWithoutSubdomain = url => {
const urlParts = new URL(url).hostname.split('.');
return urlParts
.slice(0)
.slice(-(urlParts.length === 4 ? 3 : 2))
.join('.');
};
const hostName = getDomainWithoutSubdomain(process.env.NEXTAUTH_URL);
console.log("HOSTNAME", hostName);
const options = {
secret: process.env.NEXTAUTH_SECRET,
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
pages: {
signIn: '/signin'
},
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
return true;
},
async redirect({ url, baseUrl }) {
return baseUrl;
},
async session({ session, user, token }) {
return { ...session, ...user };
},
async jwt({ token, user, account, profile, isNewUser }) {
return token;
}
},
cookies: {
sessionToken: {
name: process.env.NODE_ENV === 'production' ? `__Secure-next-auth.session-token` : 'next-auth.session-token',
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: process.env.NODE_ENV === 'production' ? true: false,
domain: '.' + hostName
}
}
}
}
export default (req, res) => NextAuth(req, res, options)
When I use getSession in the subdomain application I receive a null object, what can I do to solve this? Feel free to ask for anything for more details!
Spent ages looking for a solution...
Solution:
https://github.com/nextauthjs/next-auth/discussions/4089#discussioncomment-2290660
TLDR; You cannot use localhost subdomains as intended. You must use example.com and app.example.com. To set these go to the hosts file in you system.
Follow the steps in the github post if needed

There is no matching message handler error in NestJs TCP E2E test

I'm playing around with Microservice architecture using NestJs. I've made a simplified repository with a few services that communicate over TCP with a mix of message and event patterns.
I have moved on to writing E2E tests for the using Supertest, and while I'm able to run the needed microservice, the requests respond with {"error": "There is no matching message handler defined in the remote service.", "statusCode": 500}
GatewayService: HTTP Rest Api where the E2E tests are run. Calls the service
AuthService: NestJs microservice running on 0.0.0.0:3001 by default
configService: a simple service that returns information needed to set up the services, like host and port. I have tried eliminating it from the test and hardcoding the values.
The E2E test file
import { INestApplication, ValidationPipe } from '#nestjs/common';
import { ClientProxy, ClientsModule, Transport } from '#nestjs/microservices';
import { Test, TestingModule } from '#nestjs/testing';
import * as request from 'supertest';
import { configService } from '../src/config.service';
import { RpcExceptionFilter } from '../src/filters/rpc-exception.filter';
import { AppModule } from './../src/app.module';
describe('AuthenticationController (e2e)', () => {
let app: INestApplication;
let authClient: ClientProxy;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
AppModule,
ClientsModule.register([
{
...configService.getServiceConfigs().authService,
transport: Transport.TCP,
},
]),
],
}).compile();
// Setup the app instance
app = moduleFixture.createNestApplication();
// Setup the relevant micorservice(s)
app.connectMicroservice({
transport: Transport.TCP,
name: configService.getServiceConfigs().authService.name,
options: configService.getServiceConfigs().authService.options,
});
app.startAllMicroservices();
// Add request validation
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
}),
);
// Add needed filters
app.useGlobalFilters(new RpcExceptionFilter());
await app.init();
authClient = app.get(configService.getServiceConfigs().authService.name);
await authClient.connect();
console.log('authClient', authClient);
});
describe('POST /auth/login', () => {
it('Should return status 200 and a user object with access token', () => {
return (
request(app.getHttpServer())
.post('/auth/login')
.send({ username: 'exmple#user.com', password: 'password' })
// .expect(200)
.expect((response) => {
console.log('response', response.body);
expect(response.body).toHaveProperty('id');
expect(response.body).toHaveProperty('username');
expect(response.body).toHaveProperty('accessToken');
})
);
});
});
afterAll(async () => {
await app.close();
await authClient.close();
});
});
I have attempted adding a provider which I've used before when working with Grpc as the transport layer (this is TCP). Didn't change anything.
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
...
providers: [
{
provide: 'AUTH_SERVICE',
useFactory: () => {
return ClientProxyFactory.create({
transport: Transport.TCP,
options: { host: 'localhost', port: 3001 },
});
},
},
],
I know that the microservice starts up and the gateway service is able to connect to it since when printing the authClient: Client proxy it returns a correct object with URL 0.0.0.0:3001. If I change the URL, or the name of the service in any part of the setup then errors about missing providers show, further confirming that it is supposedly correctly set up.
One of the best guides I've found on this matter. Sadly it doesn't work for my code.

Nuxt.js multiple external API calls with axios proxy

I'm using multiple external APIs with Nuxt.js and axios, bet I have problems with SSR. When requests are coming from client-side this config is working and proxy is changing url, bet when requests are coming from server (on app page reload) proxy not hitting and axios using baseURL, which is one for all requests.
nuxt.config.js
axios: {
proxy: true
},
proxy: {
'/api/': {
target: process.env.FIRST_API_URL,
pathRewrite: {
'^/api/': ''
}
},
'/api2/': {
target: process.env.SECOND_API_URL,
pathRewrite: {
'^/api2/': ''
}
}
},
Api call in one of Vuex store actions as example:
export const actions: ActionTree<CoreState, RootState> = {
async fetchItems ({ commit }) {
await this.$axios.$get('/api2/items').then((response) => {
commit('SET_ITEMS', response.data)
})
}
}
Action is dispatching from component asyncData method:
async asyncData ({ store }) {
await store.dispatch('items/fetchItems')
}
How to make this work both from client-side and server-side ?

Proxy only POST requests (or any other HTTP method) through Webpack Dev Server?

Is there any way to only allow POST requests to be proxied using Webpack Dev Server? My app uses /login for GET requests and unfortunately it is being proxied to my other host regardless of HTTP method.
// Serve the Relay app
const compiler = webpack(config);
appServer = new WebpackDevServer(compiler, {
contentBase: '/public/',
proxy: {
'/login': `http://localhost:${GRAPHQL_PORT}`, // only for POST?
},
publicPath: '/js/',
stats: {
colors: true,
chunks: false,
},
historyApiFallback: true
});
Yes, there is. You can use bypass parameter.
// Serve the Relay app
const compiler = webpack(config);
appServer = new WebpackDevServer(compiler, {
contentBase: '/public/',
proxy: {
'/login': {
target: `http://localhost:${GRAPHQL_PORT}`, // only for POST?
bypass: function(req, res, proxyOptions) {
if(req.method != 'POST') return false;
}
}
},
publicPath: '/js/',
stats: {
colors: true,
chunks: false,
},
historyApiFallback: true
});
documentation Webpack 1
documentation Webpack 2

Webpack-dev-server not sending requests to external domain via proxy

I'm trying to use the webpack-dev-server proxy configuration to send api requests to an external domain and I can't seem to get it working.
Here's my config:
var path = require('path')
module.exports = {
entry: './client/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'assets'
},
devServer: {
contentBase: 'public',
proxy:{
'/api/v1*': {
target: 'http://laravelandwebpack.demo/',
secure: false
}
}
}
}
So, anytime my app makes a request with the uri /api/v1... it should send that request to http://laravelandwebpack.demo.
In my Vue app, I'm using the vue-resource to make the requests and I'm defaulting all requests with the needed uri prefix:
var Vue = require('vue')
Vue.use(require('vue-resource'))
new Vue({
el: 'body',
http: {
root: '/api/v1', // prefix all requests with this
headers:{
test: 'testheader'
}
},
ready: function (){
this.$http({
url: 'tasks',
method: 'GET'
}).then(function (response){
console.log(response);
}, function (response){
console.error(response);
})
}
})
The URL's are being constructed correctly, but they're still pointing to localhost:8080 which is the webpack-dev-server:
I read and re-read the docs for webpack-dev-server and I can't figure out where I have it set up wrong. Any ideas?
#Linus Borg is right.
The URL's are being constructed correctly, but they're still pointing to localhost:8080 which is the webpack-dev-server:
This doesn't matter.
In my case, I want to get http://m.kugou.com/?json=true. And I am using #Vue/cli ^3.0.0-beta.15, maybe you need to modify your code according to situation.
So, here is what I did:
App.vue
axios.get('/proxy_api/?json=true').then(data => {
console.log('data', data)
})
vue.config.js
module.exports = {
devServer: {
proxy: {
// proxy all requests whose path starting with /proxy_api to http://m.kugou.com/proxy_api then remove '/proxy_api' string
'/proxy_api': {
target: 'http://m.kugou.com',
pathRewrite: {
'^/proxy_api': '/'
}
}
}
//or just change the origin to http://m.kugou.com
// proxy: 'http://m.kugou.com'
}
}
I use /proxy_api/?json=true then update it to http://m.kugou.com/?json=true by target and pathRewrite.
'/proxy_api' is used to distinguish if the url should be proxied.
Why would I use /proxy_api? Easy to distinguish.
I got the data from http://m.kugou.com/?json=true while the url in the dev-tool is http://localhost:8080/proxy_api/?json=true.
See? that doesn't matter.
I found a workaround solution for that issue. In my case I need to proxy requests to my backend for any /api/* path, so I'm bypassing any requests which does not starts with api.
Sample:
proxy: {
'*': {
target: 'http://localhost:8081',
secure: false,
rewrite: function(req) {
console.log('rewriting');
req.url = req.url.replace(/^\/api/, '');
},
bypass: function(req, res, proxyOptions) {
if (req.url.indexOf('api') !== 0) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}else{
return false;
}
}
}
}

Resources