0

私はAngularJSからユーザを認証しようとしていたとき、私は春のブートログでこの警告見ています:415 AngularJSでサポートされていないメディアタイプや春ブーツ1.4.3

[WARN ] 2017-02-04 17:09:20.085 [http-nio-8080-exec-1] DefaultHandlerExceptionResolver - Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'null' not supported 

を、ブラウザの応答があります:

415サポートされていないメディアタイプ

マイLoginController

@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); 
    } 
} 

マイAngularJSコード:

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); 
}); 

}; //ログイン機能が

を終了私は正確に同じAngularJSと全く同じ登録制御部を有している(もちろん、異なるエンドポイントとの)関数を登録しますしかし、それは完全に動作します。

私はSpring Securityを使用しているときに、というのLoginControllerが本当に必要なのでしょうか?私のセキュリティ設定:

@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); 
} 
+0

コメントを外しても差はありません。 –

+0

しかし、これはどこでチェックしますか?私が考えるように、 "/ login"の呼び出しは、LoginControllerではなくSecurityConfigクラスによって処理されます。 また、あなたはこれについて何か考えていますか?「Spring Securityを使用しているときに、エンドポイント/ログインでLoginControllerが本当に必要なのか、それともセキュリティ設定によって処理されるのでしょうか? @dur –

+0

これは解決策ですか?[link] http://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc[/link] ?私はそれを試してみるつもりです。 –

答えて

0

最後に私は答えを得ました。リクエストパラメータの代わりにjsonオブジェクトを送信しようとすると、カスタムUserNamePasswordAuthenticationFilterを使用する必要があります。それは本当です、私はPOSTを使用する必要があります。

ありがとうございます。

最後に、this postに大きなおかげです。この記事がなければ、フィルタをカスタマイズする方法はわからないでしょう。

関連する問題