Thursday, May 28, 2020

Token JWT and Spring Boot

Objectives

Today I would like to extend my previous post (https://java-architect.blogspot.com/2020/05/spring-boot-rest-api-with-security.html) and add protection API based on JWT Token. At the beginning I would like to briefly describe the idea of tokens. Below is added BPMN process flow which shows the end-to-end path (this is a simple process flow without filters, authentication controllers or authentication managers)












The token structure
Token consists of three elements:
  • Header (algorithm and type) - {"alg":"HS256"}
  • Payload  - {"sub":"user","exp":1590655192}
  • Signature (defined secret was used to create signature)


Application

I created application based on my previous post (https://java-architect.blogspot.com/2020/05/spring-boot-rest-api-with-security.html).  The main goal is to create JWT token to protect communication between server and clients. 




I selected files which I added or replaced. Let's examine the application's code. 


pom.xml

  <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>  
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-openid</artifactId>  
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>  
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>  
</dependency>


<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>



UserDTO:

@Data
public class UserDTO {
    private String username;
    private String password;
}



SecurityConfig.class


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
        public static final String prefix = "Bearer";
public static final String header = "Authorization";
        public static final String secret = Base64.getEncoder().encodeToString("artsci".getBytes());;
        public static final Long expir = new Long(3600000);

@SuppressWarnings("deprecation")
@Bean
    public UserDetailsService userDetailsService() {
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(users.username("user").password("user").roles("USER").build());
        manager.createUser(users.username("admin").password("admin").roles("USER", "ADMIN").build());
        return manager;
    }

   @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(userDetailsService());
}
   
    @Override
    protected void configure(HttpSecurity http) throws Exception {
     
        http.csrf().disable()   
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/login").permitAll()
        .anyRequest().authenticated()
        .and().addFilterBefore(new LoginFilter("/login", authenticationManager()),   
                 UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(new AuthJwtFilter(), UsernamePasswordAuthenticationFilter.class);
        http.headers().cacheControl();
    }


LoginFilter.class

public class LoginFilter extends AbstractAuthenticationProcessingFilter {
    public LoginFilter(String url, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authenticationManager);
   }

   @Override

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse
           response)
throws AuthenticationException, IOException, ServletException {
    UserDTO user = new ObjectMapper().readValue(request.getInputStream(), UserDTO.class);
     UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                                                                                 user.getUsername(),
                                                                                                 user.getPassword(),
                                                                                                 Collections.emptyList());

     return getAuthenticationManager().authenticate(token);
}

   @Override

protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
          FilterChain chain,
Authentication authResult) throws IOException, ServletException {

     String token = Jwts.builder()
            .setSubject(authResult.getName())         
            .signWith(SignatureAlgorithm.HS256, secret)
            .setExpiration(new Date(System.currentTimeMillis() + expir))
            .compact();
     response.addHeader(header, prefix + " " + token);    
     response.setContentType("application/json");
     response.setCharacterEncoding("UTF-8");
     response.getWriter().write("{\"" + header + "\":\"" + prefix + " " + token + "\"}");     
}
}

AuthJwtFilter.class

public class AuthJwtFilter extends GenericFilterBean{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
Authentication auth = null;
         if(!((HttpServletRequest) request).getHeader(header).isEmpty()) {
String claim = ((HttpServletRequest)request).getHeader(header) 
                             .replace(prefix,"").substring(1);
String user = Jwts.parser().setSigningKey(secret).parseClaimsJws(claim)
                        .getBody().getSubject();
auth = new UsernamePasswordAuthenticationToken(user, null,                                      
                             Collections.emptyList());

}
       
         SecurityContextHolder.getContext().setAuthentication(auth);
         chain.doFilter(request,response);
}
}

The results

So, our application should work correctly. Let's try to call protected API. At the beginning it is necessary to to generate token. To achieve this goal I attempt to use URL:  "/login" and pass my credential. Below is example of CURL's request.


curl --location --request POST http://localhost:8080/login --header "Content-Type: application/json" --data-raw "{\"username\":\"user\",\"password\":\"user\"}"
{"Authorization":"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkwNjU1MTkyfQ.lKZMYWVKd9OZu2nOwMjRxXjewQ-zYKQWWB4wIp1Zhi8"}

Fantastic, JWT Token was generated. Let's try to call "/regions" service using previously generated token.


curl -H "Authorization":"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkwNjU1MTkyfQ.lKZMYWVKd9OZu2nOwMjRxXjewQ-zYKQWWB4wIp1Zhi8" --request GET http://localhost:8080/regions/
[{"regionId":1,"name":"Europe"},{"regionId":2,"name":"Americas"},{"regionId":3,"name":"Asia"},{"regionId":4,"name":"Middle East and Africa"}]

It seems that the solution works exactly as I expected :)

Wednesday, May 27, 2020

Spring Security with REST API

Spring Security with REST API 

Objectives

Today I would like to dive into security topic in Spring boot application. I base on my previous post (https://java-architect.blogspot.com/2020/05/spring-boot-rest-api-with-jpa.html) with the sources. I'm going to change and add protection to the API. There are two important aspect:

  • Authentication - process of identifying the user who calls the API
  • Authorization -  process of checking user's permission to call resources

The Authentication process can base on plain text password, digest method, JWT (Java WEB Token), OAuth, SAML or other method to identify user. Besides previously mentioned methods, very often applications are protected by certificates.


The simplest way to authenticate 

So, due the topic, the simplest way to enable user authentication is to add the appropriate configuration.



























For simplification I defined users and roles in memory. Of course in production environment that data should be fetched form LDAP, Data Base or other identity server.. 


package com.main.artsci.configutarion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
       @SuppressWarnings("deprecation")
       @Bean
       public UserDetailsService userDetailsService() {
              User.UserBuilder users = User.withDefaultPasswordEncoder();
              InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
              manager.createUser(users.username("user").password("user").roles("USER").build());
              manager.createUser(users.username("admin").password("admin").roles("USER", "ADMIN").build());
               return manager;
        }
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService());
}
@Override
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/regions/complex/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
.and().httpBasic();
}
}

In "userDetailsService()" method I defined all necessary users for this test case. In "configure()" method I enabled authentication for every request and all users can have access to all resources except resource defined by path "/regions/complex/" where access has only administrator.

In addition I created SecurityWebApplicationInitializer 

public class SecurityWebApplicationInitializer
   extends AbstractSecurityWebApplicationInitializer {
}

Let's see the pom's changes. I added security libraries:

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
     </dependency>
     <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
      </dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>  
</dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-openid</artifactId>  
</dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-ldap</artifactId>  
</dependency>

  
Finally it is necessary to checks is requested resources are protected in a proper way.  

Let's see the results after fetching resource available to everyone who pass true the authentication process.
curl --user user:user http://localhost:8080/regions
[{"regionId":1,"name":"Europe"},{"regionId":2,"name":"Americas"},{"regionId":3,"name":"Asia"},{"regionId":4,"name":"Middle East and Africa"}]
The results are exactly we expect to achieve. Next what does happen if we try to fetch protected data? 
curl --user user:user http://localhost:8080/regions/complex/1
{"timestamp":"2020-05-27T07:20:00.487+0000","status":403,"error":"Forbidden", "message":"Forbidden","path":"/regions/complex/1"} 

The error occurs. There is no permission. Let's change user to admin.

curl --user admin:admin http://localhost:8080/regions/complex/1
{"regionId":1,"name":"Europe","countries":[{"countryId":"BE","name":"Belgium"},{"countryId":"CH","name":"Switzerland"},{"countryId":"DE","name":"Germany"},{"countryId":"DK","name":"Denmark"},{"countryId":"FR","name":"France"},{"countryId":"IT","name":"Italy"},{"countryId":"NL","name":"Netherlands"},{"countryId":"UK","name":"United Kingdom"}]}
And everything is correct :)

Monday, May 25, 2020

Spring boot REST API with JPA

Spring boot REST API with JPA

Objectives 

The main goal is to create small application which could evolve to microservice. The application gather data from Oracle database then expose  that data by REST service with JSON objects. There were used a few additional libraries:

  • HikariCP - additional library to manage connection pool to database    
  • Swagger - libraries to create documentation in OpenAPI standard
  • Lombok - library to reduce boilerplate code in java classes


Below is the structure of application:














































The application's code 

The model

Based on Oracle database image which was created in my previous post (https://java-architect.blogspot.com/2020/05/oracle-plsql-part-1.html) I build selected java Entities. Lombok library was very helpful to significantly reduce boilerplate java code. It was necessary to use annotation "@JsonManagedReference" and "@JsonBackReference" for protecting against getting an errors.


The Region class:
@Getter
@Setter
@ToString
@EqualsAndHashCode
@Entity
@Table(name = "REGIONS")
public class Region  {
    @Id
    @Column(name="REGION_ID")
    private Long regionId;
 
    @NotNull
    @Column(name = "REGION_NAME")
    private String name;
 
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "region")
    @JsonManagedReference
    private List<Country> countries;
 
    public Region(){
        }     
}

The Country class:
@Getter
@Setter
@ToString
@EqualsAndHashCode
@Entity
@Table(name = "COUNTRIES")
public class Country {
    @Id
    @Column(name="COUNTRY_ID")
    private String countryId;
 
    @Column(name = "COUNTRY_NAME")
    private String name; 
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "REGION_ID", nullable = false)
    @JsonBackReference
    private Region region;
 
    public Country() {
        }
}

The repository

@Repository
public interface RegionRepository extends CrudRepository<Region, Long> { Optional<Region> findById(Long id);
}

@Repository
public interface CountryRepository extends CrudRepository<Country, String>{
    Optional<Country> findById(String countryId);   

    @Query("select c from Country c where c.name = :name")
           Stream<Country> findByNameReturnStream(@Param("name") String name);
}


The service

@Transactional
@Service("regionService")
public class RegionServiceImpl implements RegionService{
@Autowired
CountryRepository countryRepository;

@Autowired
RegionRepository regionRepository;

public List<RegionDTO> getRegions() {
                List<RegionDTO> list = new ArrayList<RegionDTO>();

for(Region r : regionRepository.findAll()) {
list.add(new RegionDTO(r));
}
return list;
}

        public RegionDTO getRegionByIdv1(Long id) {
return new RegionDTO(regionRepository.findById(id).get());

}

        public RegionDTOv2 getRegionByIdv2(Long id) {

Region region = regionRepository.findById(id).get();
region.getCountries();
return  new RegionDTOv2(region);
}
}


The RestController

@RestController
@EnableSwagger2
public class BaseController  {
@Autowired
@Qualifier("regionService")
RegionService regionService;

       @RequestMapping(method = RequestMethod.GET, value = "/regions")
        public ResponseEntity<List<RegionDTO>> regions() {           
               return new ResponseEntity<List<RegionDTO>>(regionService.getRegions(), HttpStatus.OK);

        }
 
       @RequestMapping(value = "/regions/simple/{regionId}", method = RequestMethod.GET)
  public ResponseEntity<RegionDTO> getRegionById(@PathVariable("regionId") long regionId) {
RegionDTO regionDTO = regionService.getRegionByIdv1(regionId);
return new ResponseEntity<RegionDTO>(regionDTO, HttpStatus.OK);
}
 
        @RequestMapping(value = "/regions/complex/{regionId}", method = RequestMethod.GET)
public ResponseEntity<RegionDTOv2> getRegionByIdV2(@PathVariable("regionId") long             regionId) {
    RegionDTOv2 regionDTOv2 = regionService.getRegionByIdv2(regionId);
    return new ResponseEntity<RegionDTOv2>(regionDTOv2, HttpStatus.OK);
}
}


Application.properties

#spring boot configuration for Oracle
spring.datasource.url=jdbc:oracle:thin:@localhost:49161:xe
spring.datasource.username=hr
spring.datasource.password=hr
spring.datasource.driver-class-oracle.jdbc.driver.OracleDriver

#hibernate dialect config
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
spring.jackson.serialization.fail-on-empty-beans=false
spring.jpa.show-sql=true
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1

# HikariCP settings
spring.datasource.hikari.*
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=10



The results

Specification

The results can be visualized in web browser. Let's see the API's documentation.





































The output of method "/regions"

The base output of method "/regions" has:

JSON representation:























Data representation:























And the Headers:
































The output of method "/regions/complex/{regionId}"

























What else

The CRUD operations are usually mapped to HTTP method in REST web services like below:

  • CREATE -> POST
  • READ -> GET
  • UPDATE -> PUT
  • DELETE -> DELETE