Search code examples
javaspringspring-bootspring-securitybasic-authentication

How to return Basic token after logging into Spring Security?


I am using Basic authorization in my Springboot project. Once I successfully login, I can inspect the backend webpage and see that there is an Authorization with the value Basic YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA in the Network tab.

I can then use the value Basic YmNyeX323G5yb2xsdGVjaC5jb206cyE5c2RzZA to make requests via Postman to the server by setting that value as the Authorization value.

So, my question is, how can I return this value after logging in?

This is my SecurityConfiguration.java file:

@Configuration
@EnableConfigurationProperties
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    MongoUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/", "/register").permitAll().anyRequest().authenticated()
                .and().logout(logout -> logout
                        .permitAll()
                        .clearAuthentication(true)
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/")
                        .invalidateHttpSession(true)
                        .deleteCookies("JSESSIONID"))
                .httpBasic()
                .and().sessionManagement().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }

What would the end point look like that can return the basic authorization token mentioned above?


Solution

  • SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    Object details = authentication.getDetails();
    

    Try this, it might be useful, token in details