Spring Security使角度资源失败

时间:2017-03-16 17:45:25

标签: angularjs spring spring-security angular-resource

我已经在现有应用程序中实现了一个Spring Security模块,实际上看起来像是:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .antMatchers("/static/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                    .authorizeRequests()
                    //.antMatchers("/resources/**", "/").permitAll()
                    //.antMatchers("/welcome").hasRole("ADMIN") //tu mogla by byc pobrana jaka rola i te linki np tylko dla admina
                    //.anyRequest().permitAll() //reszta po zalogowaniu
                    //.antMatchers("/resources/templates/index.html").permitAll()
                    .antMatchers("/views/pages/signIn.html").permitAll()
                    .antMatchers("/views/worker/**").hasAuthority(AuthoritiesConstants.WORKER)
                    .antMatchers("/views/client/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/views/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/templates/index.html").permitAll()
                    .antMatchers("/scripts/directives/addAdmin/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/addWorker/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/assignWorkerToWash/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/header/**").permitAll()
                    .antMatchers("/scripts/directives/info/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/reservation/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/reservationReminder/**").hasAnyRole(AuthoritiesConstants.WORKER, AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/review/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/vehicle/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/vehicle/**").hasAnyRole(AuthoritiesConstants.CLIENT, AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/review/**").hasAuthority(AuthoritiesConstants.CLIENT)
                    .antMatchers("/scripts/directives/washType/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/vehicleType/**").hasAuthority(AuthoritiesConstants.ADMIN)
                    .antMatchers("/scripts/directives/wash/**").hasAuthority(AuthoritiesConstants.ADMIN)

                    //.antMatchers("/api/reservationreminder").permitAll()


                    //???
                    .antMatchers("/auth").permitAll()
                    .antMatchers("/", "/login").permitAll()
                    .antMatchers("/templates/index.html").permitAll()
                    //.antMatchers("/api/client, /api/reservation", "/api/reservationreminder", "/api/review", "/api/user", "/api/vehicle", "/api/wash", "/api/washlocation", "/api/washtype", "/api/worker").hasAnyRole(AuthoritiesConstants.WORKER, AuthoritiesConstants.CLIENT)
                    .antMatchers("/app/styles/**", "/app/js/**").permitAll()
                    .antMatchers("/build/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .logout()
                    .logoutSuccessUrl("/views/pages/login.html")
                    .permitAll()
                .and()
                    .formLogin()
                    .loginProcessingUrl("/views/pages/login.html")
                    .permitAll()

    }
}

目录树如下所示:

enter image description here

执行后我根据我在angularJS中使用的$resource模块失败了 - 在Spring Security实现之前一切正常。

失败的症状是由于Error in resource configuration for action "query". Expected response to contain an array but got an object (Request: GET /api/reservationreminder)我无法通过登录页面登录。

当我们去那项服务时,我有:

angular.module('sbAdminApp').factory('ReservationReminderService', function($resource) {

var service = $resource('/api/reservationreminder/', {id : '@id'},
    {


    });

return service;
 });

我在LoginCtrl(angular)中使用了接受数组的query()方法:

ReservationReminderService.query().$promise.then(function (res) {
            UserService.setData('reminders', res);
            UserService.setData('wasSeen', true);

            var userRoles = UserService.getRoles();
            if (userRoles.indexOf('client') > -1){
                $state.go('dashboard.myaccount');
                return;
            }

            if (userRoles.indexOf('worker') > -1){
                $state.go('dashboard.workerreservation');
                return;
            }

            $state.go('dashboard.home');
        });

所以我真的不知道为什么会失败?也许Spring Security配置出了问题?

之前非常基本的Spring Security配置是这样的:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().permitAll()
              .and()
}

然后,一切正常。

[UPDATE] 角度控制器:

angular.module('sbAdminApp').controller('LoginCtrl', function ($scope, LoginService, $http, $state, UserService, AddUserService, $q, ReservationReminderService) {

$scope.User = {};
$scope.Error = null;

$scope.login = function () {
    $scope.Error = null;
    $http.post('auth/login', $scope.User).success(function (res, a, b) {
        UserService.setUserData(res);

        ReservationReminderService.query().$promise.then(function (res) {
            UserService.setData('reminders', res);
            UserService.setData('wasSeen', true);

            var userRoles = UserService.getRoles();
            if (userRoles.indexOf('client') > -1){
                $state.go('dashboard.myaccount');
                return;
            }

            if (userRoles.indexOf('worker') > -1){
                $state.go('dashboard.workerreservation');
                return;
            }

            $state.go('dashboard.home');
        });
    }).error(function (data) {
        // jeżeli 403 - pokaz blad
        // jezeli 5xx - alert wewnetrzny blad serwera
        if (data.status == 403)
            $scope.Error = "Błędny login lub hasło";
        else alert(data.message);
    });
    //console.log('ReservationReminderService.query();', ReservationReminderService.query())
};

$scope.signInForm = function () {
    $state.transitionTo('signIn');
}
});

[更新2]

   @RestController
    @RequestMapping(value = "/api/reservationreminder")
    public class ReservationReminderController {
    @Autowired
    private ReservationReminderServiceImpl reminderService;
    @Autowired
    private WorkerServiceImpl workerService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public List<ReservationReminder>     getReservationReminderList(HttpServletRequest request) {
        Principal name = request.getUserPrincipal();
        if (name.getName() == null) {
            throw new RuntimeException("Brak sesji");
        }
        Worker workerByLogin = workerService.findWorkerByLogin(name.getName());
        List<ReservationReminder> byReservationWorkerPesel = reminderService.findByReservationWorkerPesel(workerByLogin);
        return byReservationWorkerPesel;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public void insertOrUpdate(@RequestBody List<ReservationReminder> reservationReminderList) {
        for (ReservationReminder r : reservationReminderList) {
            if (r.getChecked() == true) {
                reminderService.insertOrUpdate(r);
            }
        }

    }
}

0 个答案:

没有答案