banner



How To Pass Username And Password In Rest Template Get Call

In this post, I volition show how to use Balance Template to consume RESTful API secured with Bones Authentication. As part of this postal service, I will show how to build a Balance API that is secured with Basic Authentication.

Overview

Basic Authentication is i of the mechanisms that y'all can use to secure your REST API. In my previous postal service, I showed how to secure Balance API with Json Web Token.

Secure a Balance API with Bones Authentication

Configure a Rest API

Firstly, we will show a elementary REST API to create users or retrieve users from the database. Then, we volition secure this Remainder API with a Bones Authentication mechanism. Lastly, nosotros will evidence how to employ Bones Hallmark with Residuum Template to call this REST API.

Our Residue controller class for this API to create or call back users volition look like beneath:

                      package com.betterjavacode.restdemo.controllers;  import com.betterjavacode.restdemo.dto.UserDto; import com.betterjavacode.restdemo.managers.UserManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;  import java.util.List;  @RestController public form UserController {     @Autowired     private UserManager userManager;      @RequestMapping(value = "/user/", method = RequestMethod.GET)     public ResponseEntity> listAllUsers()     {         List                users = userManager.getAllUsers();         if(users.isEmpty())         {             return new ResponseEntity>(HttpStatus.NO_CONTENT);         }          return new ResponseEntity<>(users, HttpStatus.OK);     }      @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces =             MediaType.APPLICATION_JSON_VALUE)     public ResponseEntity                    getUser(@PathVariable("id") long id)     {         UserDto userDto = userManager.getUser(id);         if(userDto == null)         {             return new ResponseEntity<>(HttpStatus.NOT_FOUND);         }         render new ResponseEntity<>(userDto, HttpStatus.OK);     }       @RequestMapping(value = "/user/", method= RequestMethod.Postal service)     public ResponseEntity                      createUser(@RequestBody UserDto userDto)     {         UserDto user = userManager.createUser(userDto);          render new ResponseEntity<>(user, HttpStatus.OK);     }      @RequestMapping(value = "/user/{id}", method=RequestMethod.DELETE)     public ResponseEntity                        deleteUser(@PathVariable("id") long id)     {         UserDto user = userManager.getUser(id);          if(user == null)         {             render new ResponseEntity<>(HttpStatus.NOT_FOUND);         }          userManager.deleteUser(id);          render new ResponseEntity<>(HttpStatus.NO_CONTENT);     } }                                                                                                                        

Our database model grade for User will look like below:

                      bundle com.betterjavacode.restdemo.models;  import javax.persistence.*; import java.io.Serializable;  @Entity(proper name = "User") @Tabular array(name = "users") public grade User implements Serializable {     private static final long serialVersionUID = 20200816121023L;      public User()     {      }      @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     @Column(name="id", nullable=false)     private long id;      @Column(name="firstname", length=100)     private Cord firstname;      @Cavalcade(name="lastname", length=100)     individual String lastname;      @Column(name="email", length=100)     individual String email;      @Column(name="function", length=45)     individual String part;      @Column(name="enabled")     private boolean enabled;      public long getId ()     {         return id;     }      public void setId (long id)     {         this.id = id;     }      public String getFirstname ()     {         return firstname;     }      public void setFirstname (String firstname)     {         this.firstname = firstname;     }      public String getLastname ()     {         return lastname;     }      public void setLastname (String lastname)     {         this.lastname = lastname;     }      public String getEmail ()     {         return email;     }      public void setEmail (String e-mail)     {         this.email = e-mail;     }      public Cord getRole ()     {         return role;     }      public void setRole (String part)     {         this.function = function;     }      public boolean isEnabled ()     {         return enabled;     }      public void setEnabled (boolean enabled)     {         this.enabled = enabled;     } }                  

Just to make sure we understand hither that, we are using a DTO object UserDto to create and retrieve the data from the database. User is our database model object.

The UserDto object volition be equally follows:

                      bundle com.betterjavacode.restdemo.dto;  import com.betterjavacode.restdemo.models.User; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;  @JsonIgnoreProperties(ignoreUnknown = truthful) public class UserDto {     private Cord firstname;     individual Cord lastname;     private Cord electronic mail;      public UserDto(){}      public UserDto(User user)     {         this.setEmail(user.getEmail());         this.setFirstname(user.getFirstname());         this.setLastname(user.getLastname());     }      public String getFirstname ()     {         render firstname;     }      public void setFirstname (String firstname)     {         this.firstname = firstname;     }      public String getLastname ()     {         return lastname;     }      public void setLastname (Cord lastname)     {         this.lastname = lastname;     }      public Cord getEmail ()     {         return e-mail;     }      public void setEmail (String email)     {         this.electronic mail = email;     }  }                  

Once we configure our application backdrop and create the required database table, nosotros volition start the application.

Now if we execute the API through a client like Postman, we will be able to call back or create the User object.

The goal is to secure this API.

So add Spring-Security in our project build.

implementation "org.springframework.kicking:jump-boot-starter-security"

Now, if we add the annotation @EnableWebSecurity in our chief application grade like below:

                      package com.betterjavacode.restdemo;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  @SpringBootApplication @EnableWebSecurity public form RestdemoApplication { 	public static void primary(Cord[] args) 	{ 		SpringApplication.run(RestdemoApplication.class, args); 	} }                  

and if we access the API to create user, nosotros will get 401 unauthorized fault like below:

Basic Authentication with Rest Template

Basic Authentication

Traditionally, access to REST API will happen on the server-side in one case the user has logged in with hallmark.

Basic hallmark provides one of the ways to secure Balance API. It's not the most secure mode compared to OAuth or JWT based security. In Bones Authentication, a client sends Base64 encoded credentials with each request using HTTP Authorization Header.

The client will send the Authorization header with each request. At that place is e'er a possibility of compromising these credentials even when they are Base64 encoded. To avoid that, nosotros can use HTTPS.

Now from our implementation perspective, nosotros volition add a SecurityConfig class to configure security for our Residue API.

                      packet com.betterjavacode.restdemo;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.notation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {     @Override     protected void configure(HttpSecurity httpSecurity) throws Exception     {         httpSecurity                 .csrf().disable()                 .authorizeRequests().anyRequest().authenticated()                 .and()                 .httpBasic();     }      @Autowired     public void configureGlobal(AuthenticationManagerBuilder auth)             throws Exception     {         auth.inMemoryAuthentication()                 .withUser("adminuser")                 .password("{noop}adminpassword")                 .roles("USER");     } }                  

configure method in this grade volition configure basic authentication and every request coming to our controller will demand to be authorized.

configureGlobal method will add authentication of the incoming request. The requests coming through the controller will be validated for these credentials that we have configured for in-retentivity authentication.

Alarm – This is non the nearly secure way to secure your API. Definitely not with in-memory authentication. Do not use it in production.

Now if nosotros execute Rest API through POSTMAN, we will see the successful response as below:

Securing REST API with Basic Authentication

Rest Template with Bones Hallmark Case

Initially, we used POSTMAN as a client to call our Residue APIs. But in a real scenario, we won't exist using POSTMAN, you will have to phone call these APIs programmatically.

We will create a class RestClient and that volition call our APIs while building Basic Hallmark.

While using RestTemplate that Spring Kicking provides, you need to pass HttpHeaders with a RequestEntity.

                      private static HttpHeaders getHeaders ()     {         String adminuserCredentials = "adminuser:adminpassword";         Cord encodedCredentials =                 new String(Base64.encodeBase64(adminuserCredentials.getBytes()));          HttpHeaders httpHeaders = new HttpHeaders();         httpHeaders.add together("Authorization", "Basic " + encodedCredentials);         httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));         render httpHeaders;     }                  

Nosotros use exchange method from RestTemplate to call our API and HttpHeaders that contain Basic Hallmark.

The whole class RestClient will look similar below:

                      parcel com.betterjavacode.restdemo;   import com.betterjavacode.restdemo.dto.UserDto; import org.apache.tomcat.util.codec.binary.Base64; import org.json.JSONObject; import org.springframework.http.*; import org.springframework.web.client.RestTemplate;  import java.util.Arrays; import coffee.util.LinkedHashMap; import java.util.Listing;  public class RestClient {     public static final String REST_SERVICE_URL = "http://localhost:8080/user/";      private static HttpHeaders getHeaders ()     {         String adminuserCredentials = "adminuser:adminpassword";         String encodedCredentials =                 new String(Base64.encodeBase64(adminuserCredentials.getBytes()));          HttpHeaders httpHeaders = new HttpHeaders();         httpHeaders.add together("Authorization", "Basic " + encodedCredentials);         httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));         render httpHeaders;     }      private static void listAllUsers()     {         System.out.println("Getting all users");         RestTemplate restTemplate = new RestTemplate();          HttpHeaders httpHeaders = getHeaders();          HttpEntity              httpEntity = new HttpEntity<>(httpHeaders);          ResponseEntity                responseEntity = restTemplate.exchange(REST_SERVICE_URL,                 HttpMethod.Go, httpEntity, Listing.class);          if(responseEntity.hasBody())         {             List> users = responseEntity.getBody();              if(users != null)             {                 for(LinkedHashMap                    userMap: users)                 {                     System.out.println("User is " + userMap.go("firstname") + " " + userMap.get(                             "lastname"));                 }             }         }         else         {             Organisation.out.println("User not found");         }      }      public static void main (String[] args)     {         listAllUsers();          getUser(1);     }        private static void getUser(long id)     {         System.out.println("Getting a user ");          String restUrl = REST_SERVICE_URL  + id;          RestTemplate restTemplate = new RestTemplate();          HttpHeaders httpHeaders = getHeaders();          HttpEntity                      httpEntity = new HttpEntity<>(httpHeaders);          ResponseEntity                        responseEntity = restTemplate.commutation(restUrl,                 HttpMethod.GET, httpEntity, String.class);          if(responseEntity.hasBody())         {             JSONObject jsonObject = new JSONObject(responseEntity.getBody());              Organisation.out.println(jsonObject.get("firstname"));             System.out.println(jsonObject.get("lastname"));         }         else         {             System.out.println("User non establish");         }      } }                                                                                                                        

At present if nosotros execute the program, we will run into the output equally below:

Output of Rest Template call with Basic Authentication

In this postal service, we showed how to secure Rest API with Basic Authentication. If you lot enjoyed this postal service, subscribe to my web log here.

Do you want to know the fundamentals of Spring Security? I'yard launching my new book "Simplifying Jump Security" shortly. Get on my launch list to get updates and discount codes.

References

  1. Jump Rest Template –  documentation
  2. Spring Kick Balance Template – Usage

How To Pass Username And Password In Rest Template Get Call,

Source: https://betterjavacode.com/programming/how-to-use-basic-authentication-for-rest-template

Posted by: charltonthishatthe.blogspot.com

0 Response to "How To Pass Username And Password In Rest Template Get Call"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel