Laravel with JWT - 如何为只有在未经身份验证的情况下才能看到的路由创建路由组
Posted
技术标签:
【中文标题】Laravel with JWT - 如何为只有在未经身份验证的情况下才能看到的路由创建路由组【英文标题】:Laravel with JWT - How to make route group for routes that can be seen only if unauthenticated 【发布时间】:2016-10-06 11:29:33 【问题描述】:所以我正在开发一个 Angular JS x Laravel 项目。我决定使用 JWT 令牌,并且我有一些路由,如注册和登录,只有在用户未通过身份验证时才能访问。这是我的路线:
Route::group(['middleware' => ['before' => 'jwt.auth']], function ()
Route::resource('api/user', 'UsersController');
Route::resource('api/group', 'GroupsController');
Route::resource('api/project', 'ProjectsController');
Route::resource('api/lesson', 'LessonsController');
Route::get('api/authenticate/user', 'AuthenticationController@getAuthenticatedUser');
Route::get('/any', function ($any)
return view('index');
)->where('any', '.*');
);
Route::post('api/register', 'AuthenticationController@register');
Route::post('api/login', 'AuthenticationController@login');
Route::get('/any', function ($any)
return view('guest');
)->where('any', '.*');
如何为jwt.auth
路由组之外的路由创建一个路由组,只有在用户未通过身份验证时才能访问?
【问题讨论】:
【参考方案1】:您可以使用角度控制器在前端执行此操作。这是我的做法
//Controller used for the login page
whimAppControllers.controller('LoginController', ['userService', '$location', '$scope', '$http', function (userService, $location, $scope, $http)
//Upon clicking the login button this function attempts to login in the user through the API
$scope.login = function()
//Send the user supplied values to the userService in services.js when then attempts to POST to the API
userService.login(
$scope.login, $scope.userName, $scope.password,
//Upon response, if successful return the user to the main page, else return error
function(response)
$location.path('/');
,
function(response)
alert('Something went wrong with the login process. Try again later!');
);
//Clear out the fields on the login form
$scope.email = '';
$scope.userName = '';
$scope.password = '';
//If the user is already logged, redirect to the main page
if(userService.checkIfLoggedIn())
$location.path('/');
]);
在底部,它检查是否已经为用户分配了 JWT,如果是,它会重定向到主页。
在我的 service.js 文件中,userService 有这个方法来检查 JWT:
//Checks to see if token is present or not
function checkIfLoggedIn()
if(localStorageService.get('token'))
return true;
else
return false;
;
我正在使用 LocalStorageModule 来调用 localStorageService:
var whimAppServices = angular.module('whimAppServices', [
'restangular',
'LocalStorageModule',
'ngFileUpload'
]);
我正在使用 angular-local-storage 在客户端存储 JWT:https://github.com/grevory/angular-local-storage
【讨论】:
以上是关于Laravel with JWT - 如何为只有在未经身份验证的情况下才能看到的路由创建路由组的主要内容,如果未能解决你的问题,请参考以下文章