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

Securing Your Microservices With a Declarative Model — Part Two

DZone 's Guide to

Securing Your Microservices With a Declarative Model — Part Two

In this example, we'll see how to Creating an Authorization Server Used by a Resource Server.

· Microservices Zone ·
Free Resource

In this example, we'll see how to Creating an Authorization Server Used by a Resource Server.

The benefit of using Creating a Custom Authorization Server is that we've complete control over the situation to tweak the code.

OAuth 2.0 Grant Type: Resource Owner Password Credentials


AuthServer —

ServiceConfig.java

Java
 




x
17


1
package com.example.demo;
2
 
          
3
import org.springframework.context.annotation.Configuration;
4
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
5
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
6
 
          
7
@Configuration
8
public class ServiceConfig extends GlobalAuthenticationConfigurerAdapter {
9
 
          
10
    @Override
11
    public void init(AuthenticationManagerBuilder auth) throws Exception {
12
        auth.inMemoryAuthentication()
13
            .withUser("alpha").password("{noop}pass1").roles("USER")
14
            .and()
15
            .withUser("beta").password("{noop}pass2").roles("USER", "OPERATOR");
16
    }
17
}



DsSpringCloudM4AuthserverApplication.java

Java
 




xxxxxxxxxx
1
26


1
package com.example.demo;
2
 
          
3
import java.security.Principal;
4
 
          
5
import org.springframework.boot.SpringApplication;
6
import org.springframework.boot.autoconfigure.SpringBootApplication;
7
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
8
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
9
import org.springframework.web.bind.annotation.GetMapping;
10
import org.springframework.web.bind.annotation.RestController;
11
 
          
12
@SpringBootApplication
13
@EnableAuthorizationServer
14
@EnableResourceServer
15
@RestController
16
public class DsSpringCloudM4AuthserverApplication {
17
 
          
18
    public static void main(String[] args) {
19
        SpringApplication.run(DsSpringCloudM4AuthserverApplication.class, args);
20
    }
21
 
          
22
    @GetMapping(value = "/user")
23
    public Principal user(Principal user) {
24
        return user;
25
    }
26
}



Application.properties

Java
 




xxxxxxxxxx
1
13


1
server.port=9000
2
 
          
3
# This is for Non Prod env
4
#spring.security.user.name=test
5
#spring.security.user.password=test
6
#spring.security.user.roles=USER
7
 
          
8
server.servlet.context-path=/services
9
security.oauth2.client.clientId=javaHelper
10
security.oauth2.client.clientSecret=javaHelpersecret
11
security.oauth2.client.authorized-grant-types=authorization_code,refresh_token,password,client_credentials
12
security.oauth2.client.scope=toll_read,toll_report
13
 
          



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-authserver</artifactId>
13
    <version>0.0.1-SNAPSHOT</version>
14
    <name>ds-spring-cloud-m4-authserver</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
 
          



Start the server.

Secure Service

DsSpringCloudM4SecureserviceApplication.java

Java
 




xxxxxxxxxx
1
53


1
package com.example.demo;
2
 
          
3
import java.util.ArrayList;
4
 
          
5
import org.springframework.boot.SpringApplication;
6
import org.springframework.boot.autoconfigure.SpringBootApplication;
7
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
8
import org.springframework.web.bind.annotation.RequestMapping;
9
import org.springframework.web.bind.annotation.RestController;
10
 
          
11
@SpringBootApplication
12
@RestController
13
@EnableResourceServer
14
public class DsSpringCloudM4SecureserviceApplication {
15
 
          
16
    public static void main(String[] args) {
17
        SpringApplication.run(DsSpringCloudM4SecureserviceApplication.class, args);
18
    }
19
    
20
    @RequestMapping("/tolldata")
21
//  @PreAuthorize("#oauth2.hasScope('toll_read') and hasAuthority('ROLE_OPERATOR')")
22
    public ArrayList<TollUsage> getTollData() {
23
        
24
        TollUsage instance1 = new TollUsage("200", "station150", "B65GT1W", "2016-09-30T06:31:22");
25
        TollUsage instance2 = new TollUsage("201", "station119", "AHY673B", "2016-09-30T06:32:50");
26
        TollUsage instance3 = new TollUsage("202", "station150", "ZN2GP0", "2016-09-30T06:37:01");
27
        
28
        ArrayList<TollUsage> tolls = new ArrayList<TollUsage>();
29
        tolls.add(instance1);
30
        tolls.add(instance2);
31
        tolls.add(instance3);
32
        
33
        return tolls;
34
    }
35
 
          
36
    public class TollUsage {
37
        public String Id;
38
        public String stationId;
39
        public String licensePlate;
40
        public String timestamp;
41
 
          
42
        public TollUsage() {
43
        }
44
 
          
45
        public TollUsage(String id, String stationid, String licenseplate, String timestamp) {
46
            this.Id = id;
47
            this.stationId = stationid;
48
            this.licensePlate = licenseplate;
49
            this.timestamp = timestamp;
50
        }
51
    }
52
}
53
 
          



Application.properties

Java
 




xxxxxxxxxx
1


1
server.port=9001
2
server.servlet.context-path=/services
3
 
          
4
#This is needed when you're using github or facebook as resouce server
5
#security.oauth2.resource.user-info-uri=https://api.github.com/user
6
 
          
7
security.oauth2.resource.user-info-uri=http://localhost:9000/services/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
 
          



Start the Service

Secure CLI

DsSpringCloudM4SecurecliApplication.java

Java
 




xxxxxxxxxx
1
50


1
package com.example.demo;
2
 
          
3
import java.util.Arrays;
4
 
          
5
import org.springframework.boot.CommandLineRunner;
6
import org.springframework.boot.SpringApplication;
7
import org.springframework.boot.autoconfigure.SpringBootApplication;
8
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
9
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
10
import org.springframework.security.oauth2.common.AuthenticationScheme;
11
 
          
12
@SpringBootApplication
13
public class DsSpringCloudM4SecurecliApplication implements CommandLineRunner{
14
 
          
15
    public static void main(String[] args) {
16
        SpringApplication.run(DsSpringCloudM4SecurecliApplication.class, args);
17
    }
18
 
          
19
    @Override
20
    public void run(String... args) throws Exception {
21
        System.out.println("cron job started");
22
 
          
23
        ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
24
        resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
25
        resourceDetails.setAccessTokenUri("http://localhost:9000/services/oauth/token");
26
 
          
27
        //must be a valid scope or get an error; if empty, get all scopes (default); better to ask for one
28
        resourceDetails.setScope(Arrays.asList("toll_read"));
29
 
          
30
        //must be valid client id or get an error
31
        resourceDetails.setClientId("javaHelper");
32
        resourceDetails.setClientSecret("javaHelpersecret");
33
 
          
34
        //diff user results in diff authorities/roles coming out; preauth on roles fails for adam, works for barry
35
        resourceDetails.setUsername("alpha");
36
        resourceDetails.setPassword("pass1");
37
 
          
38
        OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails);
39
        //could also get scopes: template.getAccessToken().getScope()
40
        String token =  template.getAccessToken().toString();//.getValue();
41
 
          
42
        System.out.println("Token: " + token);
43
 
          
44
        String s = template.getForObject("http://localhost:9001/services/tolldata", String.class);
45
 
          
46
        System.out.println("Result: " + s);
47
    }
48
 
          
49
}
50
 
          



Here you see the output.

Spring boot

Topics:
declarative model, microservices, oauth, spring boot, spring security oauth, tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}