Spring Boot Oauth2 implementation and enable H2 console

                             Spring Boot Oauth2 enable H2 console

Purpose: In this post, we will learn how we can enable implement Oauth2. The steps are given below.

1. Setup and Create Oauth2 Project: Visit hereSpring Boot Oauth2 Implementation using in-memory DB.

Next Step. Spring Boot Parent Dependencies.


<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
Next Step. H2 Database Dependencies.

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>

Next Step. Add below line in application.properties for H2.

#server PORT
server.port=8081

#H2 database configuration
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enabling the H2 console
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
# Before run change directory
spring.datasource.url=jdbc:h2:C:/data/oauth2
# Custom H2 Console URL
spring.h2.console.path=/h2

Next Step: Login in H2 console.


After login below blank screen is view. To resolve this issue refer next step.



Next Step. To enable H2 console add yellow highlighted line in ResourceServerConfiguration.java file.


package com.bce.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "oauth2-api";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/h2/**", "/user", "/oauth/token").permitAll();
        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.antMatcher("/**").authorizeRequests().anyRequest().authenticated();

    }
}


Next Step. Check user in H2 database.




Download Code from GitHub.  Download

No comments:

Post a Comment