简体   繁体   中英

Spring boot angularjs security custom login issue

I cant make custom login page work with angularjs and spring boot security . Default browser login form only get displayed.

I am able to authenticate and authorize the user but default login page gets displayed on first time. Also i get 302 status on logout.

Angular version : 1.4.8 , using ui-router.

Below is my main js .

    'use strict';

angular
  .module('renalyxNis', [
    'ui.router','ui.bootstrap' ,'chart.js','ngAnimate','ngResource','angular-timeline'])
  .config(function($stateProvider,$urlRouterProvider,$locationProvider, $httpProvider) {

      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';




    $urlRouterProvider.otherwise('/login');

    $stateProvider

       .state('dashboard', {
        url:'/dashboard',
        controller : 'starterCtrl',
        templateUrl: 'pages/starter2.html'

    })
      .state('dashboard.home',{
        url:'/home',
        controller : 'appointmentCtrl',
        templateUrl:'pages/home.html'

      })
      .state('dashboard.session',{
        url:'/session',       
        controller : 'sessionCtrl',
        templateUrl:'pages/session.html'

      })
      .state('dashboard.shiftmanagement',{
        url:'/shiftmanagement',        
        controller : 'shiftManageCtrl',
        templateUrl:'pages/shiftmanagement.html'

      })
      .state('dashboard.dialysisconfig',{
        url:'/dialysisconfig',       
        controller : 'dialysisConfigCtrl',
        templateUrl:'pages/dialysisconfig.html'

      })
      .state('dashboard.staffconfig',{
        url:'/staffconfig',       
        controller : 'staffCtrl',
        templateUrl:'pages/staff.html'

      })

      .state('login',{
        templateUrl:'login.html',
        url:'/login'
    });

    $httpProvider.interceptors.push(function($q) {

        return {

            'responseError': function(rejection){

                var defer = $q.defer();

                if(rejection.status == 401){
                    console.dir(rejection);
                    console.log("rejected");
                    $state.go('login');
                }

                defer.reject(rejection);

                return defer.promise;

            }
        };
    });


  });

Login ctrl :

angular.module('renalyxNis')
.controller('LoginController',function($rootScope, $scope, $http, $location, $state) {

    $rootScope.authenticated = false;

  var authenticate = function(credentials, callback) {

        var headers = credentials ? {authorization : "Basic "
            + btoa(credentials.username + ":" + credentials.password)
        } : {};

        console.log("inside login");
        $http.get('user', {headers : headers}).success(function(data) {
            // $rootScope.authenticated = false;
            if (data.name) {
                $rootScope.authenticated = true;
                console.log("complete data");

                console.log(data);
                console.log('username :');
                $rootScope.username = (data.principal.username);
                $scope.username = (data.principal.username);
                console.log('auth :');
                $rootScope.roles = (data.principal.authorities); 
                console.log(data.principal.authorities);
                console.log('name');
                console.log(data.name);

                $scope.name = data.name;

            } else {
                console.log(data);
                $rootScope.authenticated = false;
            }
            callback && callback();
        }).error(function() {
            $rootScope.authenticated = false;
            callback && callback();
        });

    }

    //authenticate();
    $scope.credentials = {};
    $scope.login = function() {

        console.log("credentials");
        console.log($scope.credentials);
        authenticate($scope.credentials, function() {
            if ($rootScope.authenticated) {
                console.log("authenticated")
                // $location.path("/home");
                $state.go ('dashboard');

                $scope.error = false;
            } else {
                $state.go('login');
                //  $location.path("/login");
                $scope.error = true;
            }
        });
        console.log("in login");
    };

    $scope.logout = function() {
        $http.post('logout', {}).success(function() {
            $rootScope.authenticated = false;
            console.log("in logout");
            $state.go('login');
            //    $location.path("/login");
        }).error(function(data) {
            $rootScope.authenticated = false;
        });
    }

});

Websecurityconfig file :

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static PasswordEncoder encoder;

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("in configure1");
         http 
         .httpBasic().and()

         .authorizeRequests()
           .antMatchers( "/").permitAll()
           .anyRequest().authenticated().and()

           .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
           .permitAll().and()
           .formLogin()
           .loginPage("/login")
           .permitAll().and()         
           .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
           .csrf().csrfTokenRepository(csrfTokenRepository());

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
               // .passwordEncoder(passwordEncoder());
        System.out.println("in configure");

    }

    private CsrfTokenRepository csrfTokenRepository() {
          HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
          repository.setHeaderName("X-XSRF-TOKEN");
          return repository;
        }

    @Bean
    public PasswordEncoder passwordEncoder() {
        if(encoder == null) {
            encoder = new BCryptPasswordEncoder();
        }

        return encoder;
    }
}

CSRF header filter :

public class CsrfHeaderFilter extends OncePerRequestFilter {
      @Override
      protected void doFilterInternal(HttpServletRequest request,
          HttpServletResponse response, FilterChain filterChain)
          throws ServletException, IOException {
        CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
            .getName());
        if (csrf != null) {
          Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
          String token = csrf.getToken();
          if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);
          }
        }
        filterChain.doFilter(request, response);
      }
    }

I referred from spring.io and dave syer login examples but to no avail.

.state('login',{
    templateUrl:'login.html',
    url:'/login'

isn't specifying the LoginController so perhaps login.html doesn't get rendered properly?

When using with AngularJS be sure to use withHttpOnlyFalse(): .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

as stated in 4.1 documentation:

https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/web/csrf/CookieCsrfTokenRepository.html #withHttpOnlyFalse--

... still receiving an 302 redirect from the server to the invalidSessionUrl if you did set it using http.sessionManagement(). ... invalidSessionUrl("login url or so") http.sessionManagement(). ... invalidSessionUrl("login url or so")

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