Search code examples
spring-bootazure-active-directoryswaggerswagger-uiswagger-2.0

spring boot with swagger OAuth not working


I added swagger dependency and enabled it, and am able to see all the API but authorize API isn't working.

am using below version of swagger:

    <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
    </dependency>

Below is my code :

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            
             @Value("${security.oauth2.client.client-id}")
            public String CLIENT_ID;
             
             @Value("${security.oauth2.client.client-secret}") 
            public String CLIENT_SECRET;
            
            
            public String AUTH_SERVER = "https://login.microsoftonline.com/common/oauth2/v2.0";
            
            
            @Bean
            public Docket swaggerConfiguration() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .select()
                        //.apis(RequestHandlerSelectors.any()) 
                        //.paths(PathSelectors.ant("/api/v1/**/**"))
                        .apis(RequestHandlerSelectors.basePackage("edu.mayo.ima.ccs.rpc_backend.controller"))
                        .paths(PathSelectors.any()) 
                        .build()
                        .securitySchemes(Arrays.asList(securityScheme()))
                        .securityContexts(Arrays.asList(securityContext()))
                        .apiInfo(getApiInfo());
                
            }
            
            @Bean
            public SecurityConfiguration security() {
                return SecurityConfigurationBuilder.builder()
                    .clientId(CLIENT_ID)
                    .clientSecret(CLIENT_SECRET)
                    .scopeSeparator(" ")
                    .useBasicAuthenticationWithAccessCodeGrant(true)
                    .build();
            }
            
            private SecurityScheme securityScheme() {
                GrantType grantType = new AuthorizationCodeGrantBuilder()
                    .tokenEndpoint(new TokenEndpoint(AUTH_SERVER + "/token", "oauthtoken"))
                    .tokenRequestEndpoint(
                      new TokenRequestEndpoint(AUTH_SERVER + "/authorize", CLIENT_ID, CLIENT_SECRET))
                    .build();
        
                SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
                    .grantTypes(Arrays.asList(grantType))
                    .scopes(Arrays.asList(scopes()))
                    .build();
                return oauth;
            }
            
            private ApiInfo getApiInfo() {
                return new ApiInfo(
                        "Protocol Catalag ",
                        "",
                        "1.0.0",
                        "",
                        null,
                        "",
                        "",
                        Collections.emptyList()
                );
            }
            
            private SecurityContext securityContext() {
                return SecurityContext.builder()
                  .securityReferences(
                    Arrays.asList(new SecurityReference("spring_oauth", scopes())))
                  .forPaths(PathSelectors.any())
                  .build();
            }
            
            private AuthorizationScope[] scopes() {
                AuthorizationScope[] scopes = { 
                  new AuthorizationScope("access_as_user", "access for application")
                 };
                return scopes;
            }
    }

With the above configuration all Api are showing on the swagger but Authorize them give error. Below is the screen when Authorize buttton is clicked.

enter image description here

enter image description here

enter image description here

Help is Appreciated.!


Solution

  • Please make sure to add the access_as_user permission under API permissions in the portal and make sure the API is exposed. Application id uri is in the format api://, you can give other name to use in app. In the Example here I gave app id uri : api://my_spring_boot_api

    enter image description here

    You should then be able to see added scope under scopes.

    enter image description here

    Then select the access_as_user permission you have added .(API Permissions>add permission>My APIs > select the required app >check the permission> add permissions)

    enter image description here

    Then you may grant consent as below

    enter image description here

    enter image description here

    Here I exposed scope >> api://my_spring_boot_api/access_as_user. Make sure to use the same scope configured in portal is included in application configuration. The scope should include the exposing resource's identifier (the Application ID URI) in the code too.

    Here Ex: scopes: "api://my_spring_boot_api/access_as_user "

    and when you call web app please make sure to send Id_token and if you call graph api you may send access token.