Search code examples
springbasic-authentication

Authorise with Basic Auth every request Spring Boot


I am building a REST api with different paths that control the data input from a mobile application (which u guessed it, it plays the role of the frontend). I am still in the very first stage of the app development and now I am testing my authorisation session. I have chosen basic auth (httpBasic() - as the method is named) and I want that every request that the mobile app does to the server, I want that to be authenticated. Because, at the moment, if I authenticate once, next time, it does not require to sent the authentication data. Is this possible? This is the function for the authorisation:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/**").hasAuthority("ROLE_USER")
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and().logout()
                    .clearAuthentication(true)
                    .invalidateHttpSession(true)
                    .logoutSuccessUrl("/")
                    .permitAll();
    }

Solution

  • You can write your custom Success Handler to handle it.

    Like :

    .logout()
        .logoutSuccessHandler(new LogoutSuccessHandler() {
    
            @Override
            public void onLogoutSuccess(HttpServletRequest request,
                        HttpServletResponse response, Authentication authentication)
                    throws IOException, ServletException {
                CustomerUserDetails userDetails = (CustomerUserDetails) authentication.getPrincipal();
                String username = userDetails.getUsername();
    
                System.out.println("The user " + username + " has logged out.");
    
                response.sendRedirect(request.getContextPath());
            }
        })
        .permitAll();
    

    Check it - Here