OAuth2 Resource Server


How to secure your API with Oauth2

For more information, see the official Spring docs.


1) Add the following dependency to your pom.xml file.

<dependencyManagement>
    <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Brixton.SR5</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
    </dependendcies>
<dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
</dependencies>

2) Add the @EnableResourceServer annotation to your Spring Boot Application class

@SpringBootApplication
@EnableResourceServer
public class Oauth2ResourceServerExampleApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Oauth2ResourceServerExampleApplication.class, args);
    }

}

3) Add a ResourceServerConfigurer bean to your Application Context. This is where you map endpoints, with optional HTTP verbs, to scopes.

@Configuration
public class Oauth2ResourceServerExampleConfiguration {

    @Bean
    public ResourceServerConfigurer resourceServerConfigurer() {
        return new ResourceServerConfigurer() {
            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

                //This is used by the oauth2 library as a unique identifier of your microservice.
                // It is used to verify that your service is the intended audience of a given JWT access token.
                resources.resourceId("users");
            }

            @Override
            public void configure(HttpSecurity http) throws Exception {

                //The scopes specified here should begin with your resourceId from above.
                http.authorizeRequests()
                        .antMatchers(HttpMethod.GET, "/api/v1/person").access("#oauth2.hasScope('users.read')")
                        .antMatchers(HttpMethod.POST, "/api/v1/person").access("#oauth2.hasScope('users.write')");
            }
        };
    }

}

4) Add the security.oauth2.resource.jwt.keyUri property to your application.yml or application.properties file. This tells your new resource server where to get its authorization server's public key, which is used to verify access tokens on requests.

---
security:
  oauth2:
    resource:
      jwt.keyUri: http://sample-uaa-cf-war.cfapps.pez.pivotal.io/token_key

Code Samples

联系我们