Vue routing redirect from path '/' to another page if a condition is met - redirect

I have a Login page that is bound to the path '/'. And if I login, I go to '/home'. The problem is that if I manually type the path '/' in the url of the browser, I go to the login page again. Is there a way to redirect me to '/home' if am already logged in? I know that I can use redirect like in the code below, but I am not sure where should I declare the a variable called isLoggedIn and how to use it. Or maybe it could be better do it in the <script> section of the Login page.
{
path: '/',
name: 'Login',
component: Login,
redirect: to => {
return {path: '/orders'}
}
}

What you are looking for is called navigation guard :
you will find more information in the vue router documentation https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
And here is a quick example extracted from this page
router.beforeEach(async (to, from) => {
if (
// make sure the user is authenticated
!isAuthenticated &&
// ❗️ Avoid an infinite redirect
to.name !== 'Login'
) {
// redirect the user to the login page
return { name: 'Login' }
}
})

Related

Get token set on API on a SSR page Nextjs

I am using Spotify authentication and in the callback I set the cookie and redirect to another page:
export default async (req, res) => {
const token = await getToken(req.query.code);
res.setHeader('Set-Cookie', cookie.serialize('token', JSON.stringify(token), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: token.expires_in,
sameSite: 'strict',
path: '/',
}));
res.redirect(token ? '/cloner' : '/');
}
On '/cloner' page I do SSR where '/' is the path to the login page:
export async function getServerSideProps(ctx) {
const cookies = nookies.get(ctx);
if (!cookies.token) { // <-- is undefined
return {
redirect: {
destination: '/',
permanent: false,
}
}
}
return {
props: {}
}
}
In the getServerSideProps the token is undefined so is returning me to the login page ('/').
BUUUUUUT, if I check in the site I can see the cookie, and if I write the /cloner manually that page load just right.
If you check in the link below you will see that if you login redirect to login again. But, if you refresh the login page it sends you to the cloner page (in login I have also SSR to redirect to cloner if already login)
https://playlist-cloner.vercel.app/

Experiencing redirect loop with a protected route in Gatsby using Auth0 [duplicate]

This question already has an answer here:
Login doesn't show up in Gatsby using Auth0, withAuthenticationRequired
(1 answer)
Closed 1 year ago.
Note: This question is not a duplicate, I'm not sure why anyone is thinking that...
I’m having issue with implementing protected pages(routes) in Gatsby with Auth0
Currently, when I point the browser to localhost:8000/user/protectedpage, it goes to the login screen, and after a successful login, it comes back to that route, and the browser seems to be stuck on a loop loading between two routes.
When I tested with this, the page was doing a indefinite redirect loop while showing "Redirect..." on the page:
export default withAuthenticationRequired(ProtectedPage, {
onRedirecting: () => <div>Redirecting...</div>
});
redirectUri in Auth0Provider is set to redirectUri={window.location.origin + '/user'}
Allowed Callback URLs in the auth0 admin page, is set to, http://localhost:8000/user
If I change these routes to window.location.origin and http://localhost:8000/, then after a successful login, it’ll redirect to that page and stay there.
I need it to redirect to where it was trying to go to instead.
As in, if I navigate to localhost:8000/user/protectedpage, then after logging in, it should redirect to that route and load that page successfully, instead of being stuck in a loop like mentioned earlier.
Here are some codes:
// File structure
src
> pages
> user
> index.js
> protectedpage
index.js
gatsby-browser.js
// gatsby-browser.js
import React from 'react';
import { Auth0Provider } from '#auth0/auth0-react';
import { navigate } from 'gatsby';
const onRedirectCallback = (appState) => {
navigate(appState?.returnTo || '/', { replace: true });
};
export const wrapRootElement = ({ element }) => {
return (
<Auth0Provider
domain={process.env.AUTH0_DOMAIN}
clientId={process.env.AUTH0_CLIENTID}
redirectUri={window.location.origin + '/user'}
onRedirectCallback={onRedirectCallback}
>
{element}
</Auth0Provider>
);
};
// protectedpage.js
import React from 'react';
import { withAuthenticationRequired } from '#auth0/auth0-react';
const ProtectedPage = () => {
return (
<div>
Protected Page
</div>
);
};
export default withAuthenticationRequired(ProtectedPage);
// auth0 Application URIs
Allowed Callback URLs
http://localhost:8000/user
I'm not sure about your full implementation but to me, the fact that it gets stuck in an infinite loop could be related to the fact that you are replacing the history by removing the last visited page in:
navigate(appState?.returnTo || '/', { replace: true });
In addition, the callback is receiving an appState otherwise, it makes the history replacing but you are never providing it at (onRedirectCallback={onRedirectCallback}):
// gatsby-browser.js
import React from 'react';
import { Auth0Provider } from '#auth0/auth0-react';
import { navigate } from 'gatsby';
const onRedirectCallback = (appState) => {
navigate(appState?.returnTo || '/', { replace: true });
};
export const wrapRootElement = ({ element }) => {
return (
<Auth0Provider
domain={process.env.AUTH0_DOMAIN}
clientId={process.env.AUTH0_CLIENTID}
redirectUri={window.location.origin + '/user'}
onRedirectCallback={onRedirectCallback} //<-- here you are not providing an appState
>
{element}
</Auth0Provider>
);
};

How to specify redirectUrl after logout for Ambassador OAuth2 Filter with Keycloak?

I'm using the Ambassador OAuth2 Filter to perform OAuth2 authorization against Keycloak.
For the logout I use the the RP-initiated logout as described in the Docs of Ambassador
The logout works fine. However I could not figure out how to provide the redirect url needed for Keycloak to redirect to the Login page after successfully logged out. As a result the user stays on the blank logout page of keycloak.
The RP-initiated logout looks as follows
const form = document.createElement('form');
form.method = 'post';
form.action = '/.ambassador/oauth2/logout?realm='+realm;
const xsrfInput = document.createElement('input');
xsrfInput.type = 'hidden';
xsrfInput.name = '_xsrf';
xsrfInput.value = getCookie("ambassador_xsrf."+realm);
form.appendChild(xsrfInput);
document.body.appendChild(form);
form.submit();
I expected that Ambassador provides a way to add the redirect url as a query param or something, but I couldn't find a solution.
Are there any suggestions or workarounds?
I found this in the Ambassador documentation that could be overlooked as I did several times:
Ambassador OAuth2 Settings
protectedOrigins: (You determine these, and must register them with your identity provider) Identifies hostnames that can appropriately set cookies for the application. Only the scheme (https://) and authority (example.com:1234) parts are used; the path part of the URL is ignored.
You will need to register each origin in protectedOrigins as an authorized callback endpoint with your identity provider. The URL will look like {{ORIGIN}}/.ambassador/oauth2/redirection-endpoint.
So it looks like ambassador hard codes the redirection-endpoint (redirect_uri) that you need add to your OAuth2 client in Keycloak.
I found a solution for that, is not the best solution but you will logout using a button.
async function logout() {
const data = new URLSearchParams("realm=keycloak-oauth2-filter.ambassador")
data.append('_xsrf', getCookie("ambassador_xsrf.keycloak-oauth2-filter.ambassador"));
fetch('/.ambassador/oauth2/logout', {
method: 'POST',
body: data
})
.then(function (response) {
if (response.ok) {
return response.text()
} else {
throw "err";
}
})
.then(function (text) {
console.log(text);
})
.catch(function (err) {
console.log(err);
});
}

Laravel 5 socialize facebook login

I use auth login (out of the box). I have want to add Facebook login.
I have installed Socialize package, and In Auth/AuthController I added method fb:
public function fb()
{
return \Socialize::with('facebook')->redirect();
}
When I call http://ip/auth/fb its redirect me to http://ip/auth/login#=
Please help
First you need to create the FB project and you will have the client_id (App ID) and secret_key (App secret)
In your services configuration file: config/services.php you need to specify the facebook key like this:
'facebook' => [
'client_id' => 'client_id from fb',
'client_secret' => 'secret_key from fb',
'redirect' => 'http://your_site/your_fb_login_ok_path',
],
then you create the route:
Route::get('your_fb_login_ok_path', function ($facebook = "facebook")
{
// Get the provider instance
$provider = Socialize::with($facebook);
// Check, if the user authorised previously.
// If so, get the User instance with all data,
// else redirect to the provider auth screen.
if (Input::has('code'))
{
$user = $provider->user();
return var_dump($user);
} else {
return $provider->redirect();
}
});
This should do it.
Then remember to add this URL to your facebook redirect: http://your_site/your_fb_login_ok_path
That is the URL that FB will redirect you to after successful login.
There are a number of possibilities
You may have set the routes wrong
The Facebook Redirect Url you specified might be wrong

Zend Framework: How to redirect to original url after login?

I'm trying to implement a login system that will be smart enough to redirect a user back to the page they were on before they decided (or were forced to) go to the login page.
I know this seems like a similar question to this one, and this one, but they do not address both of my scenarios.
There are two scenarios here:
User specifically decides to go to login page:
<a href="<?php echo $this->url(array(
'controller'=>'auth',
'action'=>'login'), 'default', true); ?>">Log In</a>
User is redirected because they tried to access protected content:
if (!Zend_Auth::getInstance()->hasIdentity()) {
$this->_helper->redirector('login', 'auth');
}
How can I implement a solution for this without displaying the "redirect to" url in the address bar?
Save the destination URL in the session. I guess you have some kind of access pre-dispatch plug-in. Do it there. And then, in the login form handler, check for the destination URL in the session, and redirect to it after a successful authentication.
Sample code from my project:
class Your_Application_Plugin_Access extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
foreach (self::current_roles() as $role) {
if (
Zend_Registry::get('bootstrap')->siteacl->is_allowed(
$role,
new Site_Action_UriPath($request->getPathInfo())
)
) return; // Allowed
}
$this->not_allowed($request);
}
private function not_allowed(Zend_Controller_Request_Abstract $request) {
$destination_url = $request->getPathInfo();
// If the user is authenticted, but the page is denied for his role, show 403
// else,
// save $destination_url to session
// redirect to login page, with $destination_url saved:
$request
->setPathInfo('/login')
->setModuleName('default')
->setControllerName('login')
->setActionName('index')
->setDispatched(false);
}
...
}
Here, current_roles() always contains 'guest', which is unauthenticated user, for which Zend_Auth::hasIdentity() is false.