How to use Nuxt SSR middleware with cookies? - cookies

I have a SSR Nuxt app. There is a middleware in the page code.
I dont know is I can use js-cookies library in that middleware and if it will work as I expected. I need to get and set up the cookie in browser and also get the cookie value on the server. All this steps in the middleware.
I mean
check if cookie is set via Cookies.get(key)
if not then set up the cookie via Cookies.set(key, value)
redirect to the server where I want to get this cookie value
Code should look like
async middleware(context) {
const token = context.route.query.token;
if (!token) {
const cookieToken = Cookies.get('cookieToken');
if( !cookieToken ) {
Cookies.set('cookieTokne', nanoId());
}
const result = await context.$api.campaignNewShare.createNewShare();
context.redirect({'name': 'campaigns-new', 'query': {token: result.data.token}});
}
},
Am I able to get cookie after the set on the server and can I get it in the browser after the redirect? I need to ensure both set and get in this middleware at once.

Use nuxt universal cookies and register on your modules, this way you can access the module everywhere on your nuxt app.
Using your code as example:
async middleware(context) {
const token = context.route.query.token;
if (!token) {
const cookieToken = context.$cookies.get('cookieToken');
if( !cookieToken ) {
context.$cookies.set('cookieToken', nanoId());
}
const result = await context.$api.campaignNewShare.createNewShare();
context.redirect({'name': 'campaigns-new', 'query': {token: result.data.token}});
}
},

Related

NextJS middleware can fetch httpOnly cookies only during development?

When Using the NextJS _middleware.js cookie is fetched by it during development in localhost, but as soon as I deploy onto vercel it stops fetching the cookie.
The Cookie is httpOnly and the cookie is present on the website but is not being fetched by the middleware in production.
Here is my middleware code
import { NextResponse } from "next/server";
export async function middleware(req) {
let token = req.cookies["refreshToken"];
console.log(token);
const { origin } = req.nextUrl
const url = req.url
if (url.includes('/profile') && !token) {
return NextResponse.redirect(`${origin}/`)
}
if (token && url.includes('/profile')) {
return NextResponse.next()
}
}
Any Suggestions? or does it not work cross site ?, but I am able to store the cookie, keep that in mind.
It might be a cross-site request issue. If your backend is hosted on a different domain and you set the cookie with the SameSite attribute set to lax or strict, your frontend code won't have access to it (see MDN).

Using Postman to test OAuth Authentication Code Flow

I'm trying to use Postman to test the Authentication Code Flow - but it doesn't seem to work correctly. I'm not sure if this is IS4 or a Postman issue.
I've created a new instance using the documentation from here:
http://docs.identityserver.io/en/latest/quickstarts/0_overview.html
Created a new Client:
new Client
{
ClientId = "code",
RedirectUris =
{
"https://www.getpostman.com/oauth2/callback"
},
AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
ClientSecrets =
{
new Secret("apisecret".Sha256())
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
}
Then using Postman trying to get an id token.
I then login with either bob/bob or alice/alice and when I click the Login button it just redirects back to the login screen.
I was expecting the access token to be retrieved.
I get the same issue when also testing against the demo instance (https://demo.identityserver.io/) using the SPA client.
If I use SoapUi it works.

Virtual Hosting on Next.js app with Apollo GraphQL

I have a webapp made with Next.js and Apollo as show in example with-apollo. I want to serve multiple domains with my webapp (name-based virtual hosting). Unfortunately HttpLink of ApolloClient requires absolute server URL with domain but this makes backend app unable to recognize domain which user really visited. Is there a way to configure HttpLink with a dynamic URL based on real request or use relative URL or anything else?
Either use an Apollo Link to intercept the query and set uri property on the context
const authMiddleware = setContext((operation, { uri }) => {
return refreshToken().then(res => ({
uri: this.getURI()
})
}))
Or intercept the request with Angular's HttpClient interceptor and change the endpoint.
https://github.com/apollographql/apollo-angular/tree/master/packages/apollo-angular-link-http#options
Source: Updating uri of apollo client instance
The NextPageContext object passed to getInitialProps includes the req object when called on the server-side. So you can do something like:
WithApollo.getInitialProps = async ctx => {
const { AppTree, req } = ctx
const linkBaseUrl = req ? req.protocol + '://' + req.get('host') : ''
...
}
You can then pass this base url down to createApolloClient along with the initial state and prepend your HttpLink's url with it. On the client side, this will prepend an empty string (you only need the full URL on the server).

Can you add a cookie to request with asp.net core middleware?

Am trying to write custom middleware in the ASP.net core pipeline, as part of my invoke, would like to append/add cookie, so then next middleware in the pipeline can access those cookie.
getting compiling error on set the cookie value. Can anyone recommend work around for this.
Note: When I tried with Response.Cookie , it works but only problem is, cookie is reflecting only on next request from the browser, but I need this to be reflecting on the next middleware in the pipeline immediately after execute this.
below code snippet
public async Task Invoke(HttpContext httpContext)
{
var queryParameters = httpContext.Request.Query;
var cookies = httpContext.Request.Cookies;
if (!cookies.ContainsKey(".AspNetCore.Session")
|| cookies[".AspNetCore.Session"] != "new_key")
{
httpContext.Request.Cookies[".AspNetCore.Session"] = "new_key";
}
await _next.Invoke(httpContext);
}
You cannot use cookie's value in same request. However, you could use good old HttpContext.Items.
public async Task InvokeAsync(HttpContext context)
{
context.Request.HttpContext.Items["key"] = "Hello!";
await _next(context);
}
You then retrieve it as
var value = HttpContext.Items["key"];
In my case I have an AuthorizationHandler that performs some checks to determine the user details and whether the user is logged in. The auth handler stores some of this info in a token in the request headers, so it can be easily accessed by the controllers.
When the user is logged in, this token can be read from the HttpContext.Request.Headers in a standard controller and all is well.
When the user is not logged in, the auth handler returns failure and so the request is redirected to "/login". Sadly the token header is not preserved across the redirect, so in my LoginController the token is null.
The only way I could make the token available to both a standard controller and LoginController is to store the token in both the request headers AND response cookies. This cookie can be read from the LoginController in the HttpContext.Request.Cookies collection. I set it to be short-lived as it's only needed briefly (it'll disappear after 5 seconds)
Here is part of the code from my auth handler:
HttpRequest request = _httpContextAccessor.HttpContext.Request;
HttpResponse response = _httpContextAccessor.HttpContext.Response;
request.Headers["X-Token"] = encryptedToken;
response.Cookies.Append("TokenCookie", encryptedToken, new CookieOptions
{
MaxAge = TimeSpan.FromSeconds(5),
Secure = true,
IsEssential = true,
});

Google Apps Script and cookies

I am trying to Post and get a cookie. I am a newbie and this is a learning project for me. My impression is that if you use 'set-cookie' one should be able to see an additional 'set-cookie' in the .toSource. (I am trying to accomplish this on Google Apps Site if that makes a difference.) Am I missing something? Here is my code:
function setGetCookies() {
var payload = {'set-cookie' : 'test'};
var opt2 = {'headers':payload, "method":"post"};
UrlFetchApp.fetch("https://sites.google.com/a/example.com/blacksmith", opt2);
var response = UrlFetchApp.fetch("https://sites.google.com/a/example.com/blacksmith")
var openId = response.getAllHeaders().toSource();
Logger.log(openId)
var AllHeaders = response.getAllHeaders();
for (var prop in AllHeaders) {
if (prop.toLowerCase() == "set-cookie") {
// if there's only one cookie, convert it into an array:
var myArray = [];
if ( Array.isArray(AllHeaders[prop]) ) {
myArray=AllHeaders[prop];
} else {
myArray[0]=AllHeaders[prop];
}
// now process the cookies
myArray.forEach(function(cookie) {
Logger.log(cookie);
});
break;
}
}
}
Thanks in advance! I referenced this to develop the code: Cookie handling in Google Apps Script - How to send cookies in header?
Open to any advice.
When you aren't logged in Google Sites won't set any cookies in the response. UrlFetchApp doesn't pass along your Google cookies, so it will behave as if you are logged out.
First the cookie you want to send whose name is 'test' does not have a value. You should send 'test=somevalue'.
Second I am wondering if you are trying to send the cookie to the googlesite server and ask it to reply with the same cookie you previously sent... ?
I am thinking you are trying to act as a HTTP server beside you are a HTTP client.
As a HTTP client your role is only to send back any cookies that the HTTP server have previously sent to you (respecting the domain, expiration... params).