2016-05-06 11 views
2

私はまだ春には特に春のセキュリティで新しいです。このアプリケーションは安らかなアプリケーションです。続き@RestControllerで春のセキュリティ - JSONish CustomAuthenticationProviderの応答

@RestControllerからの抜粋です:

@RequestMapping(value = "/new", method = RequestMethod.POST) 
    @PreRegistration("new") 
    @ResponseBody 
    public ResponseEntity<Void> newUser(@RequestBody @Valid TempUser user, UriComponentsBuilder ucBuilder) { 

     registerService.addUser(user); 

     HttpHeaders headers = new HttpHeaders(); 
     headers.setLocation(ucBuilder.path("/register/{userName}").buildAndExpand(user.getUserName()).toUri()); 
     return new ResponseEntity<Void>(headers, HttpStatus.CREATED); 
    } 

CustomAuthenticationProviderからの抜粋を以下に示します。

@Override 
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { 
    final String name = authentication.getName(); 
    final String password = authentication.getCredentials().toString(); 
    if (name.equals("admin") && password.equals("system")) { 
     final List<GrantedAuthority> grantedAuths = new ArrayList<>(); 
     grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); 
     final UserDetails principal = new User(name, password, grantedAuths); 
     final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths); 
     return auth; 
    } 
    else { 
     throw new BadCredentialsException("NOT_AUTHORIZED"); 
    } 
} 

SecurityConfig:CustomAuthenticationProviderが投げたときに

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests() 
      .anyRequest().authenticated() 
      .and() 
     .requestCache() 
      .requestCache(new NullRequestCache()) 
      .and() 
     .httpBasic() 
      .and() 
     .csrf().disable(); 
} 

私が達成しようと何があります例外(例:「bad cr 「完全な認証が必要です...」という応答をカスタマイズし、レスポンスボディにJSON形式で戻したいと考えています。

私が行ったことは、新しい例外を作成し、AOPを使用してそれを呼び出すことです。しかし、それは動作していないようです。私も@ControllerAdviceを使用しようとしましたが、CustomAuthenticationProviderがコントローラの外にあるので、うまく動作しないようです(おそらく)。

答えて

0

あなたはAccessDeniedExceptionをキャッチし、次のように設定ファイルでExceptionTranslationFilter後にフィルタを追加することができ、カスタムフィルタを作成することができる場合があります

http.addFilterAfter(customExceptionTranslationFilter, ExceptionTranslationFilter.class) 

例外をキャッチした後、あなたが応答を使用することができますがあなたが望むように応答するオブジェクト。

これで、コントローラにスローしたい他の例外を処理する機能を追加することもできます。

+0

に読むことができます"addFilterAfter"を追加したとき、リクエストは永久に無効になります。ログインしても正しいです。何か案が? – lxnx

1

これにはより良い方法があります。あなたは、AuthenticationEntryPointインターフェイスを実装している春のセキュリティの設定とクラスにauthenticationEntryPointを追加する必要があります。このような何か:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests() 
      .antMatchers("/login").permitAll() 
      .anyRequest().authenticated() 
      .and() 
     .requestCache() 
      .requestCache(new NullRequestCache()) 
      .and() 
     .httpBasic() 
     // --> begin change: new lines added 
      .and() 
     .exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint()) 
     // <-- end change 
      .and() 
     .csrf().disable(); 

}

AuthExceptionEntryPointクラス、JSON JacksonObjectMapper生産するために使用:春のセキュリティ設定について

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint { 
    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, 
         AuthenticationException authException) 
         throws IOException, ServletException { 

     List<String> errors = new ArrayList<>(); 
     errors.add("Unauthorized"); 
     response.setContentType("application/json"); 
     response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 
     try { 
      ObjectMapper mapper = new ObjectMapper(); 
      mapper.writeValue(response.getOutputStream(), errors); 
     } catch (Exception e) { 
      throw new ServletException(); 
     } 
    } 
} 

詳しい情報あなたは、それはのように思えるSpring docs

+0

答えをいただきありがとうございます。しかし、まだ同じエラーが残っています。有効な資格情報を持つログインも "AuthExceptionEntryPoint"をトリガーします。どのようなヒントでこれをデバッグするためにチェックすることができますか? – lxnx

+0

'org.springframework.security'パッケージのロギングを有効にして質問に添付します(有効な認証情報が有効でない場合) – D0dger

+0

authExceptionを出力しようとしました:org.springframework.security.authentication.InsufficientAuthenticationException:このリソースにアクセスするためには完全な認証が必要です – lxnx

関連する問題