API Gateway Ocelot not redirecting - ocelot

Im using newest Ocelot for net6.
Trying to test out a simple redirect without SSL to get a grasp of it.
{
"Routes": [
{
"DangerousAcceptAnyServerCertificateValidator": true,
"DownstreamPathTemplate": "/nft",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "http://realdnstest.com",
"Port": 80
}
],
"UpstreamPathTemplate": "/nft",
"UpstreamHttpMethod": [
"Get"
]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
Program.cs:
namespace OcelotBasic
{
public class Program
{
public static void Main(string[] args)
{
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile("ocelot.json")
.AddEnvironmentVariables();
})
.ConfigureServices(s => {
s.AddOcelot();
})
.ConfigureLogging((hostingContext, logging) =>
{
})
.UseIISIntegration()
.Configure(app =>
{
app.UseOcelot().Wait();
})
.Build()
.Run();
}
}
}
The app is running on localhost:5000 but won't redirect localhost:5000/nft to http://realdnstest.com/nft
Is there anything being missed ?

Related

VueJS and Axios handle errors properly

I am trying to raise an error during the login ... but weird thing is -> it does not work as I would expect it to ...
I am having this simple auth.service.js
class AuthService {
async login(params) {
try {
const user = (await axios.post('/authentication', { ...params })).data;
return true;
} catch (err) {
console.log(err);
throw new Error(err);
}
}
}
export default new AuthService();
The "err" has the full axios error object (as shown below)
{
"message": "Request failed with status code 401",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 401\n at settle (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1124:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1335:7)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"baseURL": "http://localhost:3030",
"method": "post",
"url": "/authentication",
"data": "{\"username\":\"admin\",\"password\":\"admin\",\"strategy\":\"local\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 401
}
what is weird is, that when I use that in my login method .. I am getting just the name and message values ... nothing else :(
methods: {
async login() {
const payload = { username: this.username, password: this.password, strategy: 'local' };
AuthService.login(payload)
.then(() => {
this.$router.push({ name: 'home' });
this.loading = false;
})
.catch(error => {
console.log(error); // THIS DOES NOT SHOW THE ENTIRE OBJECT WITH ALL KEYS
this.loading = false;
});
},
any idea why?

How to prevent to lost session after refresh in nuxt?

I am currently working on a nuxtJS app in which the session seems to be lost after any refresh (although only in dev, not while deployed). I've tried to look up in the auth module of nuxt, and have tried many answers on google, but nothing seems to work and I'm a bit lost.
nuxt.config.js
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'token',
maxAge: 3600,
global: true,
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/authentication_token', method: 'post' },
refresh: { url: '/refresh/token', method: 'post' },
logout: false,
user: { url: '/api/user', method: 'get' },
},
autoLogout: true,
},
},
},
LoginMenu.js
methods: {
async onSubmit() {
try {
const response = await this.$auth.loginWith('local', {
data: this.login,
});
if (response.status === 200) {
await this.$auth.setUser({
email: this.login.email,
password: this.login.password,
});
await this.$router.push('/');
}
else {
this.loginFail();
}
}
catch (e) {
this.loginFail();
}
},
loginFail() {
this.showError = true;
},
},
nuxt auth.js
import Middleware from './middleware'
import { Auth, authMiddleware, ExpiredAuthSessionError } from '~auth/runtime'
// Active schemes
import { RefreshScheme } from '~auth/runtime'
Middleware.auth = authMiddleware
export default function (ctx, inject) {
// Options
const options = {
"resetOnError": false,
"ignoreExceptions": false,
"scopeKey": "scope",
"rewriteRedirects": true,
"fullPathRedirect": false,
"watchLoggedIn": true,
"redirect": {
"login": "/login",
"logout": "/",
"home": "/",
"callback": "/login"
},
"vuex": {
"namespace": "auth"
},
"cookie": {
"prefix": "auth.",
"options": {
"path": "/"
}
},
"localStorage": {
"prefix": "auth."
},
"defaultStrategy": "local"
}
// Create a new Auth instance
const $auth = new Auth(ctx, options)
// Register strategies
// local
$auth.registerStrategy('local', new RefreshScheme($auth, {
"token": {
"property": "token",
"maxAge": 3600,
"global": true
},
"refreshToken": {
"property": "refresh_token",
"data": "refresh_token",
"maxAge": 2592000
},
"user": {
"property": "user"
},
"endpoints": {
"login": {
"url": "/authentication_token",
"method": "post"
},
"refresh": {
"url": "/refresh/token",
"method": "post"
},
"logout": false,
"user": {
"url": "/api/user",
"method": "get"
}
},
"autoLogout": true,
"name": "local"
}))
// Inject it to nuxt context as $auth
inject('auth', $auth)
ctx.$auth = $auth
// Initialize auth
return $auth.init().catch(error => {
if (process.client) {
// Don't console log expired auth session errors. This error is common, and expected to happen.
// The error happens whenever the user does an ssr request (reload/initial navigation) with an expired refresh
// token. We don't want to log this as an error.
if (error instanceof ExpiredAuthSessionError) {
return
}
console.error('[ERROR] [AUTH]', error)
}
})
}

NuxtJS Auth Proxy

Then using nuxtjs/auth and nuxtjs/axios nuxt is ignoring my proxy configuration.
In past I have used just axios for auth.
Now I am trying to use the #nuxtjs/auth module. Because I use a seperate backend and CORS I need to use axios proxy for auth.
But the auth stragegy local doesnt use the proxy and I dont get why. It always tries to use the nuxt URL. Seems like auth is absolutely ignoring my proxy. Can anyone help?
// nuxt.config
// ...
axios: {
proxy: true
},
proxy: {
'/api/': {
target: 'http://localhost:4000',
pathRewrite: { '^/api/': '' }
}
},
/*
** Auth Module Configuration
** See https://auth.nuxtjs.org/schemes/local.html
*/
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/api/auth/logout', method: 'post' },
user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
}
}
}
},
// ..
// Component
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
}
My Nuxt is running on http://localhost:3000
My client always tries to connect to http://localhost:3000/api/auth/login
But I need http://localhost:4000/auth/login
I use all modules up to date
I have same problem. But I use #nuxtjs/auth-next because nuxtjs/auth is outdated and use #nuxtjs/proxy to replace nuxtjs/axios proxy.
Here is my pacakge dependencies.
// pacakge.json
"dependencies": {
"#nuxtjs/auth-next": "^5.0.0-1648802546.c9880dc",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/proxy": "^2.1.0",
"nuxt": "^2.15.8",
// ...
}
Fixed nuxt.config.
// nuxt.config.ts
import type { NuxtConfig } from '#nuxt/types';
const config: NuxtConfig = {
ssr: false,
// ...ignore
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
'#nuxtjs/auth-next',
],
auth: {
strategies: {
local: {
name: 'local',
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/api/auth/logout', method: 'post' },
user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
}
// ...ignore
},
},
},
proxy: {
'/api': {
target: 'http://localhost:4000/',
secure: false,
// CORS problem need to set true,
changeOrigin: true,
pathRewrite: {
'^/api' : '/'
}
},
}
};
export default config;
If you set correct, when you run npm run dev the console should show below info.
[HPM] Proxy created: /api -> http://localhost:4000/
[HPM] Proxy rewrite rule created: "^/api" ~> "/"
[HPM] server close signal received: closing proxy server
The proxy object should be outside of the axios object, ie
axios: {
proxy: true,
// Your other configurations
}
proxy: {
'/api/': {
target: 'http://localhost:4000',
pathRewrite: { '^/api/': '' }
}
}

Angular2 - Nebular theme API endpoints

I am developing application under Angular2 and I choose Nebular frontend - https://akveo.github.io/nebular/#/home
Documentation is not really detailed for me and I am not expert in Angular2.
I am struggling in part - API endpoints https://akveo.github.io/nebular/#/docs/auth/configuring-a-provider
Where I can save the API basepoint? In which file or part of file?
Affected code:
{
baseEndpoint: 'http://...
...
My code (core.module.js):
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '#angular/core';
import { CommonModule } from '#angular/common';
import { NbEmailPassAuthProvider, NbAuthModule } from '#nebular/auth';
import { throwIfAlreadyLoaded } from './module-import-guard';
import { DataModule } from './data/data.module';
import { AnalyticsService } from './utils/analytics.service';
import { environment } from './../../environments/environment';
const NB_CORE_PROVIDERS = [
...DataModule.forRoot().providers,
...NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
delay: 3000,
login: {
rememberMe: true,
},
},
},
},
forms: {
validation: {
password: {
required: true,
minLength: 6,
maxLength: 255,
},
email: {
required: true,
}
}
}
}).providers,
AnalyticsService
];
#NgModule({
imports: [
CommonModule,
],
exports: [
NbAuthModule,
],
declarations: [],
})
export class CoreModule {
constructor(#Optional() #SkipSelf() parentModule: CoreModule) {
throwIfAlreadyLoaded(parentModule, 'CoreModule');
}
static forRoot(): ModuleWithProviders {
return <ModuleWithProviders>{
ngModule: CoreModule,
providers: [
...NB_CORE_PROVIDERS,
],
};
}
}
I'm trying to put it to work and i'm at the same part of the manual.
As i could understand, the baseEndpoint: 'http://... thing and others configuration goes on the authentication provider config variable. Looks like it's of the type NgEmailPassAuthProviderConfig (defined on #nebular/auth/providers/email-pass-auth.options).
#NgModule({
imports: [
// ...
NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
baseEndpoint: 'http://localhost:8080', // <-- here
login: {
rememberMe: true,
},
},
},
},
}),
],
});
I already managed to put it to call a api method on a Spring rest API. I can see the HttpResponse on browser with status: 200 but still getting "Oh snap!
Something went wrong." message on the NbLoginComponent.
In order to create the api correctly follow these steps
1) implement this on your localhost :
2) add this code to core.module.ts
strategies: [
NbPasswordAuthStrategy.setup({
name: 'email',
login: {
requireValidToken: false,
},
baseEndpoint: 'http://localhost:4400/api/auth/',
logout: {
redirect: {
success: '/auth/login',
failure: '/auth/login',
},
},
requestPass: {
redirect: {
success: '/auth/reset-password',
},
},
resetPass: {
redirect: {
success: '/auth/login',
},
},
errors: {
key: 'data.errors',
},
}),
],
I propose to create a proxy proxy.conf.json in the root of the project with content
{
   "/api/*": {
     "target": "http://localhost",
     "secure": false,
     "logLevel": "debug"
   }
}
then start the angular application with the command
$ ng serve --port 8097 --proxy-config proxy.conf.json
remember the * 8097 * port you mentioned in the ng serve command
to finish adding your base url as follows:
{
baseEndpoint: '/api/',
...
for more information about proxy config refer you to https://morioh.com/p/07bddb33e3ab
I hope this help

hapi-auth-cookie is protecting all routes, including static

Without applying a strategy to any routes, hapi-auth-cookie is protecting all routes, including static.
server.register(require('hapi-auth-cookie'), function (err) {
if (err) {
logError(err);
}
server.auth.strategy('session', 'cookie', true, {
password: 'things really long',
clearInvalid: true,
isSecure: false,
validateFunc: function (request, session, callback) {
cache.get(session.sid, (err, cached) => {
if (err) {
return callback(err, false);
}
if (!cached) {
return callback(null, false);
}
return callback(null, true, cached.account);
});
}
});
});
Here are my routes:
{
method: 'POST',
path: '/api/1/doSomething',
config: {
validate: {
payload: someJoyObject
},
handler: function(request, reply) {
stuff
}
}
}
and
{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: './public',
listing: false,
index: true
}
}
}
I can't load any files of my app:
{"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}
Have a look at the documentation for server.auth.strategy(). You're passing true as the 3rd argument meaning hapi will apply this strategy to all routes by default.
To disable it for your static routes either:
Don't set it as a required strategy for all routes
Disable the strategy explicitly on your directory handler route:
e.g.:
{
method: 'GET',
path: '/{param*}',
config: {
auth: false
},
handler: {
directory: {
path: './public',
listing: false,
index: true
}
}
}