Can you access the Koa Context from an Express Req object? - koa

A part of our code only has access to the Node/Express req object.
However, we need to access the Koa Request and/or Koa Context.
Does Koa inject the Context into the Node req object at all?
(Additional context: we're using Koa Multer together with S3 Multer, and S3 Multer only provides req in its callbacks, since it was obviously designed for the original Multer library.)

Related

Is there any way to cause a redirect using Apollo Server?

I'm moving all my non-graphql endpoints to GraphQL using Apollo.
One of these endpoints requires a server side redirect instead of returning data to the client.
Currently, I use express and do res.redirect but I cannot see a way to get access to the res object with Apollo. Is it possible to get it in the resolver context maybe?
Is there any chance I can do that using Apollo Server?
Here is one simple solution
First Step: Add Context while creating the apollo server object
Second Step Then access res object in your resolver context.res.redirect

How to use openid connect with flutter on spring security

I created a spring boot service that is secured by the spring-security-keycloak-adapter. As the service already knows about the (keycloak) identity provider, I don't see any point in sending the issuerUrl and clientId to the mobile client to login directly into keycloak. Instead, I want to simply call the loginurl of the service in a webview on the client. In my understanding spring should redirect to keycloak and in the end return the token.
Unfortunately all flutter packages require the clientId and issuerUrl for the oauth process
I alread tried the openid_client package for flutter
As your can see in the following code example from the official repository it requires the clientId and issuerUrl
// import the io version
import 'package:openid_client/openid_client_io.dart';
authenticate(Uri uri, String clientId, List<String> scopes) async {
// create the client
var issuer = await Issuer.discover(uri);
var client = new Client(issuer, clientId);
// create an authenticator
var authenticator = new Authenticator(client,
scopes: scopes,
port: 4000);
// starts the authentication
var c = await authenticator.authorize(); // this will open a browser
// return the user info
return await c.getUserInfo();
}
Full disclosure: I didn't write Flutter, but I did write some of the related client code for Spring Security.
Why issuerUri? The reason for this is likely for OIDC Discovery. You can use the issuer to infer the other authorization server endpoints. This cuts down on configuration for you: You don't need to specify the token endpoint, the authorization endpoint, and on and on. If you supply only the issuer, then flutter figures out the rest.
Note that with Spring Security, this is just one configuration option among multiple, but something needs to be specified either way so the app knows where to go. I can't speak for flutter, but it may just be a matter of time before it supports more configuration modes.
Why clientId? This is a security measure and is required by the specification. If someone is calling my API, I want to know who it is. Additionally, authorization servers will use this client_id to do things like make sure that the redirect_uri in the /authorize request matches what is configured for that client_id.

Vertx SockJs Eventbus Authentication

I'm trying to make a sock.js connection from the frontend to the vertx backend.
my initial try looked like this:
let token = '<the token>';
let data = {'Authorization' : 'Bearer ' + token};
let eb = new EventBus("http://localhost:8080/eventbus");
eb.onopen = function () {
eb.registerHandler('notifications', data, (err, msg) => {
// handle the response
});
}
this doesn't work since I need to send the auth data on EventBus creation, even though the official sock.js documentation states that this is not supported. Obviously now sending new EventBus("http://localhost:9090/eventbus", data) doesn't work either.
https://github.com/sockjs/sockjs-node#authorisation
my backend handler for this:
final BridgeOptions bridgeOptions = new BridgeOptions()
.addOutboundPermitted(new PermittedOptions().setAddress("notifications"))
final SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(bridgeOptions, event -> {
event.complete(true);
});
router.route("/eventbus/*").handler(ctx -> {
String token = ctx.request().getHeader("Authorization"); // null
});
router.route("/eventbus/*").handler(sockJSHandler);
whatever I tried the header field Authroization is always null.
What is the standard way to authenticate the sock.js connection and register to an eventbus request in vertx?
SockJS uses WebSockets by default. You can't add custom headers (Authorization, etc) using JavaScript WebSocket API. Read this thread for more explanation.
I see 2 ways, how you can add authorization:
Just add token parameter to URL:
let eb = new EventBus("http://localhost:8080/eventbus?token=" + token);
and here's how you can get it on a server:
String token = ctx.request().getParam("token");
Send authorization message after connecting to the server. It can be some JSON object, which contains token field.
I think, 1st option is enough, however, 2nd one can be harder to implement in terms of Event Bus and SockJS.
Since sending Authorization header is not possible, attaching a token query parameter (as described by #berserkk) is the way to go.
However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.
Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.
Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).
I think best way to secure a web-socket is using CORS check
Cross Origin Resource Sharing is a safe mechanism for allowing resources to be requested
router.route().handler(CorsHandler.create(your host origin path).allowCredentials(true));
We can add more layer of security also using sockjs :
Allow events for the designated addresses in/out of the event bus bridge
BridgeOptions opts = new BridgeOptions()
.addInboundPermitted(new PermittedOptions().setAddressRegex(Constants.INBOUND_REGEXP));

ServiceStack session handling in a Load balanced environment

I am using ServiceStack as base library in one of my project.
I have structured my application in two part API and WEB application which are separate project and repository.
Authentication should happen on the API layer and it should be cached there. I am using Ormlite cache client in API Server.
In API AppHost.cs
var dbFactory = new OrmLiteConnectionFactory("ConnectionString",SqlServerDialect.Provider);
container.RegisterAs<OrmLiteCacheClient, ICacheClient>();
container.Resolve<ICacheClient>().InitSchema();
Plugins.Add(new AuthFeature(() => new APISession(),
new IAuthProvider[] {
new APICredentialsAuthProvider(new AppSettings())
}));
In APICredentialsAuthProvider i am saving session which gets stored in Db in CacheEntry table
I am authenticating the user in Web application via ajax call using apiurl/auth which return the AuthenticateResponse with sessionId with it.
I am updating this sessionId to cookie as s-id and later in pre request filter based on the request type it is being updated in ss-id or ss-pid.
//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
System.Net.Cookie cookie = req.Cookies["s-id"];
req.Cookies["ss-id"] = cookie;
req.SetSessionId(cookie.Value)
});
This approach does not fetch the session from cache which is Ormlite in my case and respective configuration in provided in Web and Api application.
What is the best way to achieve this?
However i am able to access the session by using cache client
//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
System.Net.Cookie cookie = req.Cookies["s-id"];
req.Cookies["ss-id"] = cookie;
req.SetSessionId(cookie.Value);
APISession cachedSession = GetCacheClient(req).Get<APISession(SessionFeature.GetSessionKey(cookie.Value));
WEBSession session.PopulateWith<WEBSession, APISession>(cachedSession);
});
this works fine and i am able to fetch the session, but by putting this in pre request filter increases the db calls from my web application (on each request).
Is there any alternate solution available to achieve the same?
Thanks in advance!!
If you are load balancing multiple Web Apps behind the same domain then using any of the distributed Caching Providers like OrmLiteCacheClient will send ServiceStack's ss-id/ss-pid Cookies when making a request to either of the Apps:
http://example.org/app1 -> http://internal:8001/
/app2 -> http://internal:8002/
/app3 -> http://internal:8003/
Then as long as each app is configured with the same OrmLiteCacheClient a Session created in one App would be visible in all 3 Apps.
You can prevent further DB access for retrieving the Session for that request by setting it on IRequest.Items, e.g:
req.Items[Keywords.Session] = session;
Then any access to the Session for that Request will be resolved from the IRequest Items Dictionary instead of hitting the DB.
Another alternative Auth solution that will let you authenticate in all 3 Apps is to use the stateless JWT Auth Provider.

OWIN Authentication Server for multiple applications

I am in the process of implementing a solution that has an MVC client (lets call this CLIENT at localhost:4077/) with a WebAPI service (called API at localhost:4078/)
I have implemented OWIN OAuth in the API but wanted to know whether the OWIN could be implemented in a separate solution (lets call it AUTH at localhost:4079/token) to generate the token for the CLIENT, then the CLIENT passes this to the API (as the Bearer authorisation token)
The reason i am querying this is that there is likely to be additional WebAPI services that will be accessed by the CLIENT and i'd like to use OWIN between the client and all API services.
The issue is i am not sure if the token generated by the AUTH service could be used to authorise all requests on the CLIENT and all API services.
Has anyone implemented anything like this and if so could you provide an example, i am pretty new to OWIN and OAUTH so any help would be greatly appreciated
Separating the authorization server from the resource server is extremely easy: it will even work without any extra code if you use IIS and if you have configured identical machine keys on both applications/servers.
Supporting multiple resource servers is a bit harder to implement with the OWIN OAuth2 server if you need to select which endpoints an access token can gain access to. If you don't care about that, just configure all your resource servers with the same machine keys, and you'll be able to access all your APIs with the same tokens.
To have more control over the endpoints that can be used with an access token, you should take a look at AspNet.Security.OpenIdConnect.Server - a fork of the OAuth2 server that comes with OWIN/Katana - that natively supports this scenario: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server.
It's relatively easy to set up:
Add a new middleware issuing tokens in your authorization server application (in Startup.cs):
app.UseOpenIdConnectServer(new OpenIdConnectServerOptions
{
Provider = new AuthorizationProvider()
});
Add new middleware validating access tokens in your different API servers (in Startup.cs):
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// AllowedAudiences MUST contain the absolute URL of your API.
AllowedAudiences = new[] { "http://localhost:11111/" },
// X509CertificateSecurityTokenProvider MUST be initialized with an issuer corresponding to the absolute URL of the authorization server.
IssuerSecurityTokenProviders = new[] { new X509CertificateSecurityTokenProvider("http://localhost:50000/", certificate) }
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// AllowedAudiences MUST contain the absolute URL of your API.
AllowedAudiences = new[] { "http://localhost:22222/" },
// X509CertificateSecurityTokenProvider MUST be initialized with an issuer corresponding to the absolute URL of the authorization server.
IssuerSecurityTokenProviders = new[] { new X509CertificateSecurityTokenProvider("http://localhost:50000/", certificate) }
});
Finally, add a new OpenID Connect client middleware in your client app (in Startup.cs):
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Some essential parameters have been omitted for brevity.
// See https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/dev/samples/Mvc/Mvc.Client/Startup.cs for more information
// Authority MUST correspond to the absolute URL of the authorization server.
Authority = "http://localhost:50000/",
// Resource represents the different endpoints the
// access token should be issued for (values must be space-delimited).
// In this case, the access token will be requested for both APIs.
Resource = "http://localhost:11111/ http://localhost:22222/",
});
You can have a look at this sample for more information: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/dev/samples/Mvc/
It doesn't use multiple resource servers, but it shouldn't be hard to adapt it using the different steps I mentioned. Feel free to ping me if you need help.

Resources