Spring security with @RestController - JSONish CustomAuthenticationProvider response

后端 未结 2 2050
挽巷
挽巷 2021-01-15 02:38

I still new with Spring especially spring security. This application is Restful application.

Following is snippet from @RestController :



        
相关标签:
2条回答
  • 2021-01-15 02:59

    You may be able to create a custom filter that can catch an AccessDeniedException and add the filter after ExceptionTranslationFilter in the configuration file in the following way:

    http.addFilterAfter(customExceptionTranslationFilter, ExceptionTranslationFilter.class)
    

    After catching the exception, you can use the response object to respond in the way you'd like.

    You can then also add the ability to work with other exception you may want to throw in your Controllers.

    0 讨论(0)
  • 2021-01-15 03:03

    There is a better way for this. You should add authenticationEntryPoint in spring security config and class, which implements AuthenticationEntryPoint interface. Something like this:

    @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 class, for producing JSON Jackson ObjectMapper used:

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

    More information about spring security config you can read on Spring docs

    0 讨论(0)
提交回复
热议问题