{{announcement.body}}
{{announcement.title}}

Securing Your Microservices With a Declarative Model — Part One

DZone 's Guide to

Securing Your Microservices With a Declarative Model — Part One

Learn how to make the Authorization Code and Authorization Grant Type to secure the micro-services using Spring Security OAuth2.

· Microservices Zone ·
Free Resource

In this tutorial, we'll learn how to make the Authorization Code and Authorization Grant Type to secure the micro-services using Spring Security OAuth2.

Spring Security OAuth2 has a lot of great features and advantages — 

  • Protocol for conveying authorization
  • Provides authorization flow for various clients
  • Obtains limited access to the user account
  • Separates idea of user and client
  • Access token carries more than Identity.
  • NOT an authentication scheme.

Actors in an OAuth 2.0 Scenario

OAuth 2.0

Abstract OAuth Flow

OAuth Flow

OAuth 2.0 Grant Type: Authorization Code

grant type

Use @EnableResourceServerannotation it can combine AuthZ and Resource servers user-info-URI and token-info-URI properties  OAuth2RestTemplate  bean.

Secure UI Code

OAuth2RestTemplateConfig.java

Java
 




x
13


1
import org.springframework.context.annotation.Bean;
2
import org.springframework.context.annotation.Configuration;
3
import org.springframework.security.oauth2.client.OAuth2ClientContext;
4
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
5
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
6
 
          
7
@Configuration
8
public class OAuth2RestTemplateConfig {
9
    @Bean
10
    public OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
11
        return new OAuth2RestTemplate(resource, context);
12
    }
13
}



ReportController.java

Java
 




xxxxxxxxxx
1
72


1
import java.util.ArrayList;
2
 
          
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
5
import org.springframework.core.ParameterizedTypeReference;
6
import org.springframework.http.HttpMethod;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10
import org.springframework.security.oauth2.client.OAuth2ClientContext;
11
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
12
import org.springframework.security.oauth2.common.OAuth2AccessToken;
13
import org.springframework.stereotype.Controller;
14
import org.springframework.ui.Model;
15
import org.springframework.web.bind.annotation.RequestMapping;
16
 
          
17
@Controller
18
@EnableOAuth2Sso
19
public class ReportController extends WebSecurityConfigurerAdapter {
20
 
          
21
    @Autowired
22
    private OAuth2ClientContext clientContext;
23
 
          
24
    @Autowired
25
    private OAuth2RestTemplate oauth2RestTemplate;
26
 
          
27
    @RequestMapping("/")
28
    public String loadHome() {
29
        return "Home";
30
    }
31
 
          
32
    @RequestMapping("/reports")
33
    public String loadReports(Model model) {
34
 
          
35
        OAuth2AccessToken t = clientContext.getAccessToken();
36
        System.out.println("Token: " + t.getValue());
37
 
          
38
        ResponseEntity<ArrayList<TollUsage>> tolls = oauth2RestTemplate.exchange(
39
                "http://localhost:9001/services/tolldata", HttpMethod.GET, null,
40
                new ParameterizedTypeReference<ArrayList<TollUsage>>() {
41
                });
42
 
          
43
        model.addAttribute("tolls", tolls.getBody());
44
 
          
45
        return "reports";
46
    }
47
 
          
48
    public static class TollUsage {
49
 
          
50
        public String Id;
51
        public String stationId;
52
        public String licensePlate;
53
        public String timestamp;
54
 
          
55
        public TollUsage() {
56
        }
57
 
          
58
        public TollUsage(String id, String stationid, String licenseplate, String timestamp) {
59
            this.Id = id;
60
            this.stationId = stationid;
61
            this.licensePlate = licenseplate;
62
            this.timestamp = timestamp;
63
        }
64
 
          
65
    }
66
 
          
67
    @Override
68
    protected void configure(HttpSecurity http) throws Exception {
69
        http.authorizeRequests().antMatchers("/", "/login**").permitAll().anyRequest().authenticated();
70
    }
71
}
72
 
          



DsSpringCloudM4SecureuiApplication.java

Java
 




xxxxxxxxxx
1
11


1
import org.springframework.boot.SpringApplication;
2
import org.springframework.boot.autoconfigure.SpringBootApplication;
3
 
          
4
@SpringBootApplication
5
public class DsSpringCloudM4SecureuiApplication {
6
 
          
7
    public static void main(String[] args) {
8
        SpringApplication.run(DsSpringCloudM4SecureuiApplication.class, args);
9
    }
10
 
          
11
}



Pom.xml

Java
 




xxxxxxxxxx
1
86


1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
    <modelVersion>4.0.0</modelVersion>
5
    <parent>
6
        <groupId>org.springframework.boot</groupId>
7
        <artifactId>spring-boot-starter-parent</artifactId>
8
        <version>2.2.6.RELEASE</version>
9
        <relativePath /> <!-- lookup parent from repository -->
10
    </parent>
11
    <groupId>com.example</groupId>
12
    <artifactId>ds-spring-cloud-m4-secureui</artifactId>
13
    <version>0.0.1-SNAPSHOT</version>
14
    <name>ds-spring-cloud-m4-secureui</name>
15
    <description>Demo project for Spring Boot</description>
16
 
          
17
    <properties>
18
        <java.version>1.8</java.version>
19
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
20
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
21
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22
    </properties>
23
 
          
24
    <dependencies>
25
        <dependency>
26
            <groupId>org.springframework.cloud</groupId>
27
            <artifactId>spring-cloud-starter-oauth2</artifactId>
28
        </dependency>
29
        <dependency>
30
            <groupId>org.springframework.boot</groupId>
31
            <artifactId>spring-boot-starter-security</artifactId>
32
        </dependency>
33
        <dependency>
34
            <groupId>org.springframework.boot</groupId>
35
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
36
        </dependency>
37
        <dependency>
38
            <groupId>org.springframework.boot</groupId>
39
            <artifactId>spring-boot-starter-web</artifactId>
40
        </dependency>
41
        <dependency>
42
            <groupId>org.projectlombok</groupId>
43
            <artifactId>lombok</artifactId>
44
            <optional>true</optional>
45
        </dependency>
46
        <dependency>
47
            <groupId>org.springframework.boot</groupId>
48
            <artifactId>spring-boot-starter-test</artifactId>
49
            <scope>test</scope>
50
            <exclusions>
51
                <exclusion>
52
                    <groupId>org.junit.vintage</groupId>
53
                    <artifactId>junit-vintage-engine</artifactId>
54
                </exclusion>
55
            </exclusions>
56
        </dependency>
57
        <dependency>
58
            <groupId>org.springframework.security</groupId>
59
            <artifactId>spring-security-test</artifactId>
60
            <scope>test</scope>
61
        </dependency>
62
    </dependencies>
63
 
          
64
    <dependencyManagement>
65
        <dependencies>
66
            <dependency>
67
                <groupId>org.springframework.cloud</groupId>
68
                <artifactId>spring-cloud-dependencies</artifactId>
69
                <version>${spring-cloud.version}</version>
70
                <type>pom</type>
71
                <scope>import</scope>
72
            </dependency>
73
        </dependencies>
74
    </dependencyManagement>
75
 
          
76
    <build>
77
        <plugins>
78
            <plugin>
79
                <groupId>org.springframework.boot</groupId>
80
                <artifactId>spring-boot-maven-plugin</artifactId>
81
            </plugin>
82
        </plugins>
83
    </build>
84
 
          
85
</project>
86
 
          



Home.html

HTML
 




xxxxxxxxxx
1
19


1
<!DOCTYPE HTML>
2
<html xmlns:th="http://www.thymeleaf.org">
3
<head>
4
    <title>Secure App Home Page</title>
5
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
    <!-- Latest compiled and minified CSS -->
7
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></link> 
8
</head>
9
<body>
10
    <div class="row">
11
        <div class="col-md-2"></div>
12
        <div class="col-md-8">
13
            <h1>Secure App Home Page</h1>
14
        </div>
15
        <div class="col-md-2"></div>
16
    </div>
17
 
          
18
</body>
19
</html>


reports.html

Java
 




xxxxxxxxxx
1
27


1
<!DOCTYPE HTML>
2
<html xmlns:th="http://www.thymeleaf.org">
3
<head>
4
    <title>JavaHelper Training: Secure App Reports Page</title>
5
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
    <!-- Latest compiled and minified CSS -->
7
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></link> 
8
</head>
9
<body>
10
<div class="row">
11
    <div class="col-md-2"></div>
12
    <div class="col-md-8">
13
            <h1>JavaHelper Training: Secure App Reports Page</h1>
14
        
15
            <table class="table table-striped">
16
                <tr><th>Station ID</th><th>Plate</th><th>Timestamp</th></tr>
17
                <tr th:each="toll : ${tolls}">
18
                    <td th:text="${toll.stationId}"></td>
19
                    <td th:text="${toll.licensePlate}"></td>
20
                    <td th:text="${toll.timestamp}"></td>
21
                </tr>
22
            </table>
23
    </div>
24
    <div class="col-md-2"></div>
25
</div>
26
</body>
27
</html>



Application.yml — Below ClientId and ClientSecret intended to use only locally and not for Prod ready application.

Java
 




xxxxxxxxxx
1
11


1
security:
2
  oauth2:
3
    client:
4
      clientId: bd1c0a783ccdd1c9b9e4
5
      clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
6
      accessTokenUri: https://github.com/login/oauth/access_token
7
      userAuthorizationUri: https://github.com/login/oauth/authorize
8
      clientAuthenticationScheme: form
9
    resource:
10
      userInfoUri: https://api.github.com/user
11
      preferTokenInfo: false



Start this code.


Secure Service Code —

DsSpringCloudM4SecureserviceApplication.java

Java


Application.properties

Java
 




xxxxxxxxxx
1


1
server.port=9001
2
server.servlet.context-path=/services
3
security.oauth2.resource.user-info-uri=https://api.github.com/user



Pom.xml

Java
 




xxxxxxxxxx
1
78


1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
    <modelVersion>4.0.0</modelVersion>
5
    <parent>
6
        <groupId>org.springframework.boot</groupId>
7
        <artifactId>spring-boot-starter-parent</artifactId>
8
        <version>2.2.6.RELEASE</version>
9
        <relativePath /> <!-- lookup parent from repository -->
10
    </parent>
11
    <groupId>com.example</groupId>
12
    <artifactId>ds-spring-cloud-m4-secureservice</artifactId>
13
    <version>0.0.1-SNAPSHOT</version>
14
    <name>ds-spring-cloud-m4-secureservice</name>
15
    <description>Demo project for Spring Boot</description>
16
 
          
17
    <properties>
18
        <java.version>1.8</java.version>
19
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
20
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
21
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22
    </properties>
23
 
          
24
    <dependencies>
25
        <dependency>
26
            <groupId>org.springframework.boot</groupId>
27
            <artifactId>spring-boot-starter-security</artifactId>
28
        </dependency>
29
        <dependency>
30
            <groupId>org.springframework.boot</groupId>
31
            <artifactId>spring-boot-starter-web</artifactId>
32
        </dependency>
33
        <dependency>
34
            <groupId>org.springframework.cloud</groupId>
35
            <artifactId>spring-cloud-starter-oauth2</artifactId>
36
        </dependency>
37
 
          
38
        <dependency>
39
            <groupId>org.springframework.boot</groupId>
40
            <artifactId>spring-boot-starter-test</artifactId>
41
            <scope>test</scope>
42
            <exclusions>
43
                <exclusion>
44
                    <groupId>org.junit.vintage</groupId>
45
                    <artifactId>junit-vintage-engine</artifactId>
46
                </exclusion>
47
            </exclusions>
48
        </dependency>
49
        <dependency>
50
            <groupId>org.springframework.security</groupId>
51
            <artifactId>spring-security-test</artifactId>
52
            <scope>test</scope>
53
        </dependency>
54
    </dependencies>
55
 
          
56
    <dependencyManagement>
57
        <dependencies>
58
            <dependency>
59
                <groupId>org.springframework.cloud</groupId>
60
                <artifactId>spring-cloud-dependencies</artifactId>
61
                <version>${spring-cloud.version}</version>
62
                <type>pom</type>
63
                <scope>import</scope>
64
            </dependency>
65
        </dependencies>
66
    </dependencyManagement>
67
 
          
68
    <build>
69
        <plugins>
70
            <plugin>
71
                <groupId>org.springframework.boot</groupId>
72
                <artifactId>spring-boot-maven-plugin</artifactId>
73
            </plugin>
74
        </plugins>
75
    </build>
76
 
          
77
</project>
78
 
          



Run this code as well.

Now hit the http://localhost:8080/ in the browser it will ask you to authenticate using the GitHub account. After a successful login and allowing permissions, you should be able to see below.

JavaHelper

This is performing the OAuth2 with the GitHub account and redirected back to the reports page.

Even you can execute through POSTMAN.

POSTMAN

Using Token, you should be able to get the response.

token

Topics:
microservices ,oauth ,spring security oauth ,tutorial ,ui code

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}