skip to Main Content

I have configured Azure AD credentials in my Spring Boot project’s application.propertiesfile using the dependency spring-cloud-azure-starter-active-directory. Here is the configuration:

spring.cloud.azure.active-directory.enabled=true
spring.cloud.azure.active-directory.profile.tenant-id=${TENANT_ID_ENV_VAR}
spring.cloud.azure.active-directory.credential.client-id=${CLIENT_ID_ENV_VAR}
spring.cloud.azure.active-directory.credential.client-secret=${CLIENT_SECRET_ENV_VAR}

Application Code:

@RestController
public class HelloController {

    @GetMapping("/user")
    public String getUserInfo(
            @AuthenticationPrincipal OAuth2User principal) {

        // Retrieve the email or username from the principal
        String userName = principal.getAttribute("preferred_username");

        // Return a response with the user's email
        return "Hello: " + userName;
    }
}

Currently, I am encountering an error on a particular Azure Web App (ASP) server: [invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: I/O error on POST request for "https://login.microsoftonline.com/0d993ad3-fa73-421a-b129-1fe5590103f3/oauth2/v2.0/token": login.microsoftonline.com: Temporary failure in name resolution.

I have cross-checked the AD credentials and I am getting a successful response in the local environment and a different web app as well. After referring to some Google documents and links mentioned below, I have made the necessary adjustments, but I am still getting the same error on that web app.

Spring Boot Version:

<properties>
        <java.version>17</java.version>
        <spring-cloud-azure.version>5.5.0</spring-cloud-azure.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.azure.spring</groupId>
            <artifactId>spring-cloud-azure-starter-active-directory</artifactId>
        </dependency>
    </dependencies>

Links: https://learn.microsoft.com/en-us/answers/questions/1600366/receiving-(invalid-token-response)-error-while-imp

Could u please guide me how to fix/resolve this issue and and what are the posssible reasons for this issue.

Here is the error screenshot for your reference.
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    To resolve the [invalid_token_response] error in Azure Web App, change the DNS zone option in the networking section from 'Custom' to 'Default' (Azure provided).


  2. I successfully retrieved the username and access token both locally and in the Azure Web App.

    HelloController.java :

    I have modified the HelloController as below to retrieve the Access Token.

                @RegisteredOAuth2AuthorizedClient("azure") OAuth2AuthorizedClient authorizedClient,
                @RequestParam(name = "path", required = false) String path) {
            if (principal != null) {
                String userName = principal.getAttribute("preferred_username");
                String accessToken = authorizedClient.getAccessToken().getTokenValue();
                return "Hello: " + userName + "<br>Access Token: " + accessToken;
            } else {
                return "No user found";
            }
        }
    }
    

    Below is the complete HelloController class.

    import org.springframework.security.core.annotation.AuthenticationPrincipal;
    import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
    import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
    import org.springframework.security.oauth2.core.user.OAuth2User;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
    
        @GetMapping("/user")
        public String AccessManagementEntity(
                @AuthenticationPrincipal OAuth2User principal,
                @RegisteredOAuth2AuthorizedClient("azure") OAuth2AuthorizedClient authorizedClient,
                @RequestParam(name = "path", required = false) String path) {
            if (principal != null) {
                String userName = principal.getAttribute("preferred_username");
                String accessToken = authorizedClient.getAccessToken().getTokenValue();
                return "Hello: " + userName + "<br>Access Token: " + accessToken;
            } else {
                return "No user found";
            }
        }
    }
    

    SecurityConfig.java :

    I added the signin logic in the SecurityConfig class.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.web.server.ServerHttpSecurity;
    import org.springframework.security.web.server.SecurityWebFilterChain;
    
    @Configuration
    public class SecurityConfig {
        public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
            http
                    .csrf(ServerHttpSecurity.CsrfSpec::disable)
                    .authorizeExchange(exchange -> exchange
                            .pathMatchers("/signin/**", "/login/oauth2/**").permitAll()
                            .anyExchange().authenticated()
                    )
                    .oauth2Login(oauth2 -> oauth2
                            .authenticationSuccessHandler((webFilterExchange, authentication) -> {
                                return webFilterExchange.getExchange().getResponse().setComplete();
                            })
                    );
            return http.build();
        }
    }
    

    application.properties :

    spring.security.oauth2.client.registration.azure.client-id=<clientID>
    spring.security.oauth2.client.registration.azure.client-secret=<clientSecret>
    spring.security.oauth2.client.registration.azure.client-authentication-method=client_secret_basic
    spring.security.oauth2.client.registration.azure.authorization-grant-type=authorization_code
    spring.security.oauth2.client.registration.azure.redirect-uri=http://localhost:8080/login/oauth2/code/azure
    spring.security.oauth2.client.registration.azure.scope=openid,profile,email
    spring.security.oauth2.client.registration.azure.client-name=Azure
    spring.security.oauth2.client.provider.azure.issuer-uri=https://login.microsoftonline.com/<tenantID>/v2.0
    spring.security.oauth2.client.provider.azure.authorization-uri=https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/authorize
    spring.security.oauth2.client.provider.azure.token-uri=https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
    spring.security.oauth2.client.provider.azure.user-info-uri=https://graph.microsoft.com/oidc/userinfo
    azure.activedirectory.tenant-id=<tenantID>
    logging.level.org.springframework.security=DEBUG
    

    pom.xml :

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    

    I have added the redirect URI for both local and Azure Web Apps in the service principal under Authentication, as shown below.

    http://localhost:8080/login/oauth2/code/azure
    
    <AzureWebAppsURL>/login/oauth2/code/azure
    

    enter image description here

    Local Output :

    enter image description here

    I successfully retrieved the userName and Access Token in the browser.

    enter image description here

    Note : Before deploying, make sure to update the redirect URI in the application.properties file to the web app URL as shown below.

    spring.security.oauth2.client.registration.azure.redirect-uri=<AzureWebAppsURL>/login/oauth2/code/azure
    

    Azure Web App Output :

    I successfully retrieved the userName and Access Token in the Azure Web apps.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search