Azure OAuth throwing Invalid Credentials error in production. But works locally.

Thalha 0 Reputation points
2025-02-11T11:56:46.0133333+00:00

Hello, this is my current spring boot security config.

package com.example.emp_management.config;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Value("${azure.tenant-id}")
    private String tenantId;
    @Value("${ipro.login.redirect-uri}")
    private String loginRedirectUri;
    @Value("${ipro.logout.redirect-uri}")
    private String logoutRedirectUri;
    @Value("${ipro.homepage-url}")
    private String iproHomePageUrl;
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeRequests(auth -> auth
                        .anyRequest().authenticated())
                .oauth2Login(oauth2 -> oauth2
                        .successHandler(new AuthenticationSuccessHandler() {
                            @Override
                            public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {
                                response.sendRedirect(loginRedirectUri);
                            }
                        }))
                .logout(logout -> logout
                        .logoutSuccessHandler(azureLogoutSuccessHandler())
                        .deleteCookies("JSESSIONID")
                        .invalidateHttpSession(true));
        return http.build();
    }
    private LogoutSuccessHandler azureLogoutSuccessHandler() {
        SimpleUrlLogoutSuccessHandler handler = new SimpleUrlLogoutSuccessHandler();
        handler.setDefaultTargetUrl(
                "https://login.microsoftonline.com/" + tenantId +
                        "/oauth2/v2.0/logout?post_logout_redirect_uri=" + logoutRedirectUri);
        return handler;
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList(iproHomePageUrl, "https://login.microsoftonline.com/**"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

and my properties file looks like this


spring:
  security:
    oauth2:
      client:
        provider:
          azure:
            issuer-uri: https://login.microsoftonline.com/xxxxxxxx/v2.0             
			user-name-attribute: name
        registration:
          azure-dev:
            provider: azure
            client-id: xxxxxxxxxxxxxxxxxxxxxxxxxxxx
            client-secret: xxxxxxxxxxxxxxxxxxxxxxxx
            redirect-uri: http://localhost:8082/api/login/oauth2/code/azure-dev
            scope:
              - openid
              - email
              - profile
azure:
    tenant-id: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ipro:
  homepage-url: http://localhost:3000/
  login:
    redirect-uri: http://localhost:3000/dashboard
  logout:
    redirect-uri: http://localhost:3000/


In production I replaced the localhost with domain name and also I updated the redirect URL in Authentication section of App in Azure AD.

But once I give me cred to login it redirects me to this page

User's image

the url is like --> https://[domain]/api/login?error

I couldn't figure out the cause. Please help.

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Microsoft Security | Microsoft Entra | Microsoft Entra ID
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Kancharla Saiteja 5,485 Reputation points Microsoft External Staff Moderator
    2025-02-14T07:41:36.9866667+00:00

    Hi Thalha,

    Thank you for posting your query on Microsoft Q&A. I am Saiteja from Q&A will be assisting you with your query.

    Based on your query, I understand the issue is coming up when you are trying to connect over public which works well while working locally.

    I believe this might happened due to the http request which is working well with your local host URL. Could you please try to use override with /oauth/token which permits basic authentication.

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
    }
    

    You can use this link as reference in order to configure the spring boot using Azure OAuth. Also, here are the key samples which might also help you in configuring the same: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/main/aad/spring-cloud-azure-starter-active-directory/web-client-access-resource-server/aad-web-application

    I hope this information is helpful. Please feel free to reach out if you have any further questions.

    If the answer is helpful, please click "Accept Answer" and kindly "upvote it". If you have extra questions about this answer, please click "Comment"


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.