2015-09-07 113 views
0

我在前端使用Angular,并在后端使用弹簧安全处理安全性。Spring security&Angular

但是,Spring sec不验证用户。对于有效和无效的凭证,其行为都是相同的。我想为无效的用户或密码和有效凭证的用户数据捕获“不良凭据”。 我的问题是什么,我该如何处理?谢谢

春季安全配置

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

@Bean 
public JdbcUserDetailsManager userDetailsManager(AuthenticationManager authenticationManager, DataSource dataSource) { 
    JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager(); 
    userDetailsService.setDataSource(dataSource); 
    userDetailsService.setAuthenticationManager(authenticationManager); 
    return userDetailsService; 
} 

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder()); 
} 

@Override 
public void configure(WebSecurity web) throws Exception { 
    web.ignoring().antMatchers("/webjars/**", "/resources/**", "/js/**", "/public/**"); 
} 

@Override 
@Bean 
public AuthenticationManager authenticationManagerBean() throws Exception { 
    return super.authenticationManagerBean(); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception {   
    http 
      .authorizeRequests().antMatchers("/login").permitAll().and() 
      .authorizeRequests().antMatchers("/index").permitAll().and() 

      .authorizeRequests().anyRequest().hasRole("USER").and() 
      .exceptionHandling() 
      .accessDeniedPage("/index?authorization_error=true") 
      .and() 

      .csrf() 
      .csrfTokenRepository(csrfTokenRepository()) 
      .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable() 
      .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class) 

      .logout() 
      .logoutSuccessUrl("/index") 
      .logoutUrl("/logout.do") 
      .and() 

      .formLogin() 
      .usernameParameter("j_username") 
      .passwordParameter("j_password") 
      .failureUrl("/index?authentication_error=true") 
      .loginPage("/index") 
      .loginProcessingUrl("/j_security_check") 
      .and() 

      .sessionManagement().maximumSessions(1); 
} 

private Filter csrfHeaderFilter() { 
    return new 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); 
     } 
    }; 
} 

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

}

角控制器:

 var loginService = function() { 
     var deferred = $q.defer(); 
     $http.post(contextPath + '/j_security_check', {j_username: $scope.credentials.j_username, j_password: $scope.credentials.j_password}). 
      success(function (data) { 
       deferred.resolve(data); 
      }). 
      error(function (data, status, header, config) { 
       $log.warn(data, status, header(), config); 
       deferred.reject(status); 
      }); 
     return deferred.promise; 
    }; 
    $scope.login = function() { 
     loginService().then(function (result) { 
      console.log(result); 
      $state.go('dashboard'); 
     }, function (result) { 
      switch (result) { 
       case 401: 
        $scope.message = "Error " + result + ": username or password is not correct"; 
        break; 
       case 403: 
        $scope.message = "Error " + result + ": username or password is not correct"; 
        break; 
       default : 
        $scope.message = "Error " + result + " :unknown error"; 
      } 
     }) 
    }; 

谢谢

回答

2

UPDATE:

检查THI有类似的SO问题,它有示例angularjs http拦截器直接获取csrf参数并在所有请求中添加标头。

默认angularJS

原因不中link

上班提到默认情况下AngularJS提供了一种机制来实现跨站请求伪造,但是这个机制的工作,只有饼干。由于Spring Security通过将令牌设置为HTTP参数来工作,所以AngularJS提供的开箱即用解决方案将无法工作。

作为spring-security-csrf-token-interceptor项目的文件中提到的 - “一个AngularJS拦截器,设置春季安全CSRF令牌信息在所有HTTP请求” - 它的工作原理是使头调用接收X-CSRF-TOKEN,它然后存储该令牌并将其与每个http请求一起发送出去。

摘要:在上述项目中添加角度拦截器以解决您的问题。检查该github项目中提到的示例。

+0

谢谢你真的帮我。现在我可以登录。但我需要我的用户数据,比如他的角色,我怎样才能发送这些数据,而不是只是'好',作为回应 – farhad

+0

你的意思是登录后你需要用户角色的回应吗?我没有看到你的代码在哪里授予ROLE_USER给登录用户。 –

+0

是的,你是正确的,但如果我想访问用户数据,如名称,电子邮件,......我如何处理 – farhad