'How to add the username and passwords to a request in java spring

I'm currently trying to add security to my spring application and just want to know how can i add the credentials to the request so that it has the security access to access the getall URL This is the post code on my client aplication

    public void save(String object) {
    try {
        final String URL = "http://localhost:8080/opject/getall";
        Gson g = new Gson();
        String jsonsStrinjg = g.toJson(object);
        String p = post(URL, jsonsStrinjg);
        if (p != null)
            JOptionPane.showMessageDialog(null,"Sucsess");
        else
            JOptionPane.showMessageDialog(null,"Fail");


    }catch (Exception e){
        JOptionPane.showMessageDialog(null,e.getMessage());
    }
}

public String post(final String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    try(Response response= client.newCall(request).execute()){
        return response.body().string();

    }

}

This is the code on my server side handling security

@Configuration
@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication()
          .withUser("Admin")
          .password(encoder().encode("123"))
          .roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,"**/getall").hasRole("ADMIN")
                .and()
                .csrf().disable()
                .formLogin().disable();
}
@Bean
public PasswordEncoder encoder(){

    return  new BCryptPasswordEncoder();


}

} So is there something I have to add tot he body or the request where i can add the password and username.



Solution 1:[1]

You have to add Basic Auth to your header which will look like,

Authorization: Basic <base64encode(userid:password)>

To achieve that,

String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );

Then set the authHeader to http header when you call api.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bala