I am attempting to access a route defined in my routes/web.php file:
Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth');
I am not logged in. The Authenticate.php middleware file attempts to redirect me back to the login page:
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('');
}
}
}
I have also tried using return route('/'); in the Authenticate.php middleware.
My routes/web.php file has a default route which works fine if I go to the page manually:
Route::get('/', [ConsoleController::class, 'loginForm'])->middleware('guest');
However, the Authenticate.php is causing the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [] not defined.
http://localhost:8888/dashboard
And it points to the following line of code:
public function route($name, $parameters = [], $absolute = true)
{
if (! is_null($route = $this->routes->getByName($name))) {
return $this->toRoute($route, $parameters, $absolute);
}
throw new RouteNotFoundException("Route [{$name}] not defined.");
}
I have found many similar posts on and off Stack Overflow, but none of those solutions have helped.
Am I naming my default route wrong? Can I not use this route in my Authenticate.php middleware? Any help would be appreciated.
Issue is, you are using route() method of Laravel, which expect route name as a parameter but you are passing actual url.
In your routes/web.php file, add name to your route as
Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth')->name('dashboard');
Then in your Authenticate middleware file,
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('dashboard');
}
}
}
Related
This question extends this question. The _middleware in Next.js with import { NextResponse } from "next/server"; can be used for JWT authentication but blocks all the routes including images. This means that if you have images that you want to load in the redirect route by CSS or Image, will not load. The code below blocks address bar redirect and allows image load. Access Token would probably be better
Update: after some debugging, this is what I've come up with. The previous code that I wrote does not let you be redirected to the home page after login. The reason being that the _Middleware seems to runs before /api/login and based on the prev conditional, just redirects them to the login again and returns void (_Middleware "includes" on redirect).
This updated code allows /api/login to be routed on without a refresh token and sends them back to login if they navigate through address bar without a token
import { NextResponse } from "next/server";
export default function (req: {
url?: any;
cookies?: any;
}): void | NextResponse {
const { cookies } = req;
const url: string = req.url;
const refreshToken: string | undefined = cookies?.refresh_token_extreme;
const baseUrl: string = "http://localhost:3000";
// vercel.svg is used in /login
const unprotectedPaths: string[] = [
`${baseUrl}/login`,
`${baseUrl}/favicon.ico`,
`${baseUrl}/vercel.svg`,
`${baseUrl}/_next/webpack-hmr`,
`${baseUrl}/attachables/campus-images/image1.jpg`,
`${baseUrl}/attachables/mnhs-images/logos/login_logo.png`,
`${baseUrl}/attachables/mnhs-images/logos/mnhs_favicon_og.ico`,
]
if (unprotectedPaths.includes(url)) {
return void 0;
} else if (!refreshToken && url === "http://localhost:3000/api/login") {
return NextResponse.next();
} else if (!refreshToken) {
return NextResponse.redirect(`${baseUrl}/login`);
} else {
return NextResponse.next();
}
}
Middleware will be invoked for every route in your project. The following is the execution order:
headers from next.config.js
redirects from next.config.js
Middleware (rewrites, redirects, etc.)
beforeFiles (rewrites) from next.config.js
Filesystem routes (public/, _next/static/, Pages, etc.)
afterFiles (rewrites) from next.config.js
Dynamic Routes (/blog/[slug])
fallback (rewrites) from next.config.js
There are two ways to define which paths Middleware will run on:
Custom matcher config
Conditional statements
for more informations
I'm struggling to redirect a user to the correct location in an ASP.NET Core middleware.
What I'm trying to archieve is an application relative redirect, so if my app runs as https://www.example.com/app any link generated should be rooted there.
E.g. ~/path should resolve to /app/path.
I tried using UrlHelperFactory, but that's MVC and needs an ActionContext, which does not exist inside a middleware.
Heres a code sample of my middleware:
app.Map(pathMatch, appMap =>
{
// [... more code ...]
appMap.Use((context, next) =>
{
var nextUrl = context.Request.Query["nextUrl"];
var applicationBase = context.Request.PathBase;
if (nextUrl == StringValues.Empty || !UrlUtil.IsLocalUrl(nextUrl[0]))
{
context.Response.Redirect(applicationBase);
}
else
{
context.Response.Redirect(applicationBase.Add(nextUrl[0]));
}
return Task.CompletedTask;
});
});
I am trying to use the Auth0 for social login but I keep getting an exception of an undefined reference.
This is the authentication service
import { Injectable } from '#angular/core';
import { tokenNotExpired } from 'angular2-jwt';
// Avoid name not found warnings
declare var Auth0Lock: any;
#Injectable()
export class AuthService {
// Configure Auth0
lock = new Auth0Lock('I have set the ID correctly here', 'and the domain as well', {});
constructor() {
// Add callback for lock `authenticated` event
this.lock.on("authenticated", (authResult) => {
localStorage.setItem('id_token', authResult.idToken);
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
};
public logout() {
// Remove token from localStorage
localStorage.removeItem('id_token');
};
}
I injected the services and configured providers. Everything is wired correctly, but it just won't find Auth0Lock even though defined.
Each time it reaches lock = new Auth0Lock('ID', 'DOMAIN', {}); it bombs out.
I replaced declare var Auth0Lock: any; with const Auth0Lock = require('auth0-lock').default; and that fixed the problem.
The accepted answer is good. I did get a Cannot find name 'require' error.
Rather than using 'declare const require', I imported like so:
import Auth0Lock from 'auth0-lock';
I needed to add to index.html:
<script src="https://cdn.auth0.com/js/lock/10.8/lock.min.js"></script>
via https://github.com/auth0/lock/issues/588
I have a controller with a particular method to login:
public function login() {
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
// not logged
$this->Flash->error('Your username or password is incorrect');
}
}
and default route looks like
Router::scope('/', function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
});
after user is logged in CakePHP throws an error
Error: A route matching "/" could not be found.
None of the currently connected routes match the provided parameters.
Add a matching route to config/routes.php
when IMO it should to redirect to the page (based on a related controller) from where login method was executed.
Login code is based on that tutorial.
Any thoughts?
To solve this issue:
Please update the below lines in routes.php file
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'users', 'action' => 'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
Please do create index() in users controller.
Let me know if any issue.
We want to have 2 sets of resources for our AngularJS app (public/private) which uses RequireJS for dependency management. Basically everything on the login page would be public and once logged in, another angularjs app would be loaded (new requirejs config) that would load resources that require authentication to access.
Is there a way to configure requirejs to set an authorization header when loading resources?
It depends on what you mean by "resources" and how your server is configured. But in general - yes, since you are using AngularJS you can use the $httpProvider to inject an interceptor service.
For example, in a service:
var dependencies = ['$rootScope', 'userService'];
var service = function ($rootScope, userService) {
return {
request: function(config) {
var currentUser = userService.getCurrentUser();
var access_token = currentUser ? currentUser.access_token : null;
if(access_token) {
config.headers.authorization = access_token;
}
return config;
},
responseError: function (response) {
if(response.status === 401) {
$rootScope.$broadcast('unauthorized');
}
return response;
}
};
};
module.factory(name, dependencies.concat(service));
Then, after you configure your routes, you can use:
$httpProvider.interceptors.push( 'someService');
You can find some more information on interceptors here: https://docs.angularjs.org/api/ng/service/$http#interceptors
UPDATE
You might be able to use the text plugin to try and receive it, but I don't see the point in protecting client side code. Plus, if you want to use optimization the resources will just come in one file anyway...
config: {
text: {
onXhr: function (xhr, url) {
xhr.setRequestHeader('Authorization','Basic ' + token);
}
}
}
Refer to: custom-xhr-hooks
Another UPDATE
You could also use urlArgs (mainly used for cache invalidation) without using the text plugin:
require.config({
urlArgs: 'token='+token,
...
)}