JHipster+AngularJS:登录后按用户权限跳转对应页面的实现问题
Hey there! Let's sort out this role-based redirect issue you're facing in your AngularJS + JHipster app. As someone who's tinkered with similar JHipster auth flows before, here's a straightforward fix tailored to your scenario.
First, let's look at the gap in your current code: after a successful login, you're not checking the user's roles before redirecting. JHipster's Auth service already handles fetching user details post-login, so we can leverage that to add role-based logic.
Here's the updated login controller code with role checks:
function login(event) { event.preventDefault(); Auth.login({ email: vm.email, password: vm.password, rememberMe: vm.rememberMe }).then(function() { vm.authenticationError = false; // Fetch the logged-in user's account details (includes roles) Auth.getAccount().then(function(account) { // Check if the user has ROLE_ADMIN const isAdmin = account.authorities.includes('ROLE_ADMIN'); if (isAdmin) { // Redirect to admin-specific page (replace with your state name) $state.go('admin-dashboard'); } else { // Redirect to regular user page (replace with your state name) $state.go('user-home'); } }).catch(function() { // Fallback: if fetching account fails, redirect to a safe default $state.go('home'); }); }).catch(function() { vm.authenticationError = true; // Keep your existing login error handling here (e.g., show error message) }); }
Key details to note:
- JHipster's
Auth.getAccount(): This method returns the current user's full profile, including anauthoritiesarray that lists all their roles (likeROLE_ADMINorROLE_USER). - Route Safety: Don't forget to add role checks to your routes too, so users can't bypass the redirect by typing the URL directly. For example, in your route config:
.state('admin-dashboard', { url: '/admin/dashboard', templateUrl: 'app/admin/dashboard/dashboard.html', controller: 'AdminDashboardController', controllerAs: 'vm', resolve: { authorize: ['Auth', function(Auth) { // Block access unless user has ROLE_ADMIN return Auth.hasAuthority('ROLE_ADMIN'); }] } }) - Test Edge Cases: Try logging in with both admin and regular user accounts to confirm redirects work, and make sure login failures still show your error state correctly.
内容的提问来源于stack exchange,提问作者tmehta2442
相关产品推荐
相关产品推荐

