简体   繁体   中英

Spring Security + Angularjs redirect after login

Trying to use idea from this tutorial: https://spring.io/guides/tutorials/spring-security-and-angular-js/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and()
            .logout().and().authorizeRequests()
            .antMatchers("/index.html", "/main.html", "admin.html",  
            "/login.html", "/")         
            .permitAll().anyRequest()
            .authenticated().and().csrf().disable();
    }

Also I use angularjs ngRoute:

var myApp = angular.module('myApp',['ngRoute']);

myApp.config(['$routeProvider',
    function($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: 'main.html',
              controller: 'MainController'
        })
        .when('/admin', {
          templateUrl: 'admin.html',
              controller: 'AdminController'
        })
        .when('/login', {
          templateUrl: 'login.html',
          controller: 'LoginController'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

And so on.

But when I try to open admin page (for example /#/admin) it opens login form (from the box) and after that I expect that it should redirect me back to /#/admin, but it redirect me to /admin.html, which is out of the angular control.

How to solve this?

To address the /error redirection you can create a controller like this

@Controller
public class ErrorController {


    @RequestMapping(value="/error")
    public String error() {
        return "forward:/index.html";
    }

}

from a spring-boot perspective it should always fall in index.html where you are "giving the control to angular"

Im assuming your resources folder structure is as follows resources/static/index.html

so that index gets rendered when accesing root.

My directory structure is diffent than the one on the tutorial but it should work

Just Understood what your problem is: So in your angular config add this :

$locationProvider.html5Mode(true).hashPrefix('#');

and in the index.htm include the base tag

  <base href="<!-- @echo BASE_URL -->" target="_blank">

this will get rid of the '#' charecter and everything should work

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM