415 AngularJS和Spring Boot 1.4.3不支持的媒体类型

时间:2017-02-04 11:53:00

标签: angularjs spring spring-boot spring-security spring-restcontroller

当我尝试从AngularJS验证用户时,我在Spring Boot日志中看到了警告

@RestController
// @RequestMapping("/")
public class LoginController {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/login", method = RequestMethod.GET, 
        consumes = MediaType.APPLICATION_JSON_VALUE 
        /*produces = MediaType.APPLICATION_JSON_VALUE*/)
    public ResponseEntity<Admin> login(@RequestBody UserDTO user, BindingResult result, WebRequest request) {
        logger.info("********** Inside login of LoginController **************");

        Admin authenticatedUser = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HttpStatus httpStatus = null;
        if (authenticatedUser == null) {
            httpStatus = HttpStatus.NOT_FOUND;
        } else {
            httpStatus = HttpStatus.OK;
        }
        return new ResponseEntity<Admin>(authenticatedUser, httpStatus);
    }
}

浏览器响应是:

  

415不支持的媒体类型

我的service.login = function(user, successHandler, errorHandler) { // Obtain a CSRF token loginResources.options().$promise.then(function (response) { console.log('Obtained a CSRF token in a cookie', response); // Extract the CSRF token var csrfToken = Cookies.getFromDocument($http.defaults.xsrfCookieName); console.log('Extracted the CSRF token from the cookie', csrfToken); // Prepare the headers var headers = { 'Content-Type': 'application/json' }; headers[$http.defaults.xsrfHeaderName] = csrfToken; console.log("Before calling /login, user : ", user); // Post the credentials for logging in $http.get(ApiBasePath + '/login', user, {headers: headers}) .success(successHandler) .error(function (data, status, headers, config) { if (isCSRFTokenInvalidOrMissing(data, status)) { console.error('The obtained CSRF token was either missing or invalid. Have you turned on your cookies?'); } else { // Nope, the error is due to something else. Run the error handler... errorHandler(data, status, headers, config); } }); }).catch(function(response) { console.error('Could not contact the server... is it online? Are we?', response); });

LoginController

我的AngularJS代码:

/login

}; //登录功能结束

我有一个完全相同的注册控制器,它具有完全相同的AngularJS寄存器功能(当然具有不同的端点),但效果很好。

我怀疑一件事,当我使用Spring Security时,我真的需要端点@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/*/**").permitAll() .antMatchers("/login").permitAll() .antMatchers("/register").permitAll() .antMatchers("/", "/**/*.css", "/**/**/*,css", "/**/*.js", "/**/**/*.js").permitAll() .antMatchers("/dashboard", "/dasboard/**", "/logout").authenticated(); // Handlers and entry points http .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); http .formLogin() .successHandler(authenticationSuccessHandler); http .formLogin() .failureHandler(authenticationFailureHandler); // Logout http .logout() .logoutUrl("/logout") .logoutSuccessHandler(logoutSuccessHandler); // CORS http .addFilterBefore(corsFilter, ChannelProcessingFilter.class); // CSRF http .csrf().requireCsrfProtectionMatcher( new AndRequestMatcher( // Apply CSRF protection to all paths that do NOT match the ones below new NegatedRequestMatcher(new AntPathRequestMatcher("/", HttpMethod.OPTIONS.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/", HttpMethod.GET.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/", HttpMethod.POST.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/", HttpMethod.HEAD.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/", HttpMethod.TRACE.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/css/**", HttpMethod.GET.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/js/**", HttpMethod.GET.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/js/**/**", HttpMethod.GET.toString())), // We disable CSRF at login/logout, but only for OPTIONS methods new NegatedRequestMatcher(new AntPathRequestMatcher("/login*/**", HttpMethod.OPTIONS.toString())), new NegatedRequestMatcher(new AntPathRequestMatcher("/logout*/**", HttpMethod.OPTIONS.toString())), //Disable CSRF at register for all methods new NegatedRequestMatcher(new AntPathRequestMatcher("/register*/**", HttpMethod.OPTIONS.toString())) ) ); http .addFilterAfter(new CsrfTokenResponseCookieBindingFilter(), CsrfFilter.class); // CSRF tokens handling } @Autowired public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); auth.authenticationProvider(authProvider()); } @Bean public DaoAuthenticationProvider authProvider() { final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(encoder()); return authProvider; } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(11); } 的{​​{1}},否则安全配置会处理这个问题?我的安全配置:

<p>
 A 
 <span>die</span> 
  is thrown \(x = {-b \pm 
  <span>\sqrt</span>
  {b^2-4ac} \over 2a}\) twice. What is the probability of getting a sum 7 from
both the throws?
</p>

1 个答案:

答案 0 :(得分:0)

最后我得到了答案。确实,如果我尝试发送json对象而不是请求参数,我必须使用Custom UserNamePasswordAuthenticationFilter。这也是事实,我必须使用POST。

感谢@dur指出这一点。

最后,非常感谢this post。如果没有这篇文章,我就不会知道如何自定义过滤器。