Sending Custom JSON from Java class in case of auth failure of REST API on spring boot

by curiousengineer   Last Updated August 04, 2017 17:26 PM

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    private RESTAuthenticationEntryPoint authenticationEntryPoint;
    private RESTAuthenticationFailureHandler authenticationFailureHandler;
    private RESTAuthenticationSuccessHandler authenticationSuccessHandler;

    private UserDetailsService userDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

    protected void configure(HttpSecurity http) throws Exception {
                .realmName("KS TEST")



    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

I have pasted part of above code. I also extended three classes and injected them as bean AuthenticationEntryPoint, SimpleUrlAuthenticationFailureHandler, SimpleUrlAuthenticationSuccessHandler thinking I could extend those and try to get custom error message in case of auth failure. I get the standard spring auth failure in my REST API that works perfectly but I want to define my own class that I want to send as response at auth layer even before the resource endpoint comes into play. Like my own custom class with my own data members. Currently I get the default error in case of wrong auth

{"timestamp":1469955305299,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/secure/hello"}

This is how i execute the rest call with wrong pwd

//REST API execution example
curl  -v -u mickey:cheesee http://localhost:8080/secure/hello

If i give the right pwd things work as expected. However in wrong one, say I want to have a class that I can populate and that becomes json reponse at the auth layer. Can someone tell me what I need to do?

Answers 1

I've read about a solution using an override of an HttpSecurity method. Also, I've implemented a solution, but using Jwt library for Java.


August 04, 2017 17:25 PM

Related Questions

A simple curl command causes this ridiculousness

Updated May 15, 2018 21:26 PM

Enums as Request Parameters in Spring Boot Rest

Updated May 21, 2019 07:26 AM

How to secure the input json object in rest api

Updated September 12, 2017 09:26 AM