Pivotal + VMware: Transforming how more of the world builds software

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.


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

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.

public class Oauth2ResourceServerExampleConfiguration {

    public ResourceServerConfigurer resourceServerConfigurer() {
        return new ResourceServerConfigurer() {
            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.

            public void configure(HttpSecurity http) throws Exception {

                //The scopes specified here should begin with your resourceId from above.
                        .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.

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

Code Samples

Contact us