Spring security with @RestController - JSONish CustomAuthenticationProvider response

后端 未结 2 2071
挽巷
挽巷 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 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 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

提交回复
热议问题