0
votes

package com.example.demo;

import java.util.Arrays;
import java.util.Collections;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private final OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

public SecurityConfiguration(OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService) {
    System.out.println("loading user:" + oidcUserService);
    this.oidcUserService = oidcUserService;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
    .and().authorizeRequests()
    .anyRequest()
    .authenticated()
    .and()
    .oauth2Login()
    .userInfoEndpoint().oidcUserService(oidcUserService);
}

 @Bean
    CorsConfigurationSource corsConfigurationSource() 
    {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    configuration.setAllowedHeaders(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
    }

API:

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class AccountResource {
    
        @Autowired
        AdUserInfo adUserInfo;
    
        @CrossOrigin(origins = "http://localhost:4200")
        @GetMapping("/account")
        public AdInfo getAccount() {
            adUserInfo.setEmail("[email protected]");
            return new AdInfo();
        }
    }

Angular code:

        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        import { Observable, Subject } from 'rxjs';
        import { AdInfo } from './ad-info';
        @Injectable({
          providedIn: 'root'
        })
        export class LoginService {
          private loginUrl: string;
          constructor(private http: HttpClient) {
            this.loginUrl = 'http://localhost:8080/account';
          }
        
          public login(): Observable<AdInfo> {
            return this.http.get<AdInfo>(this.loginUrl);
          }
        
        }

Angular class:

            export class AdInfo {
                id: string;
                name: string;
                email: string;
            }

Calling from http://localhost:8080 is working fine. It goes to azure and login . as per • https://docs.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory.

Now i want to call it from Angular UI. So Localhost:4200. made a login page. Onlick login button. It is calling localhost:8080. But error in showing to redirecting to azure ad login.

ERROR: Access to XMLHttpRequest at 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=******&scope=openid%20https://graph.microsoft.com/user.read&state=a04QyhpKFkvGUvjUCRwZ834QhTgzTFYIu74M0768Co0%3D&redirect_uri=http://localhost:8080/login/oauth2/code/azure' (redirected from 'http://localhost:8080/account') from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Access to XMLHttpRequest at 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=******&scope=openid%20https://graph.microsoft.com/user.read&state=Du8JvHSEGdD3xcBft6B683mDrW8Zedppel1Xz6lBZwY%3D&redirect_uri=http://localhost:4200/login/oauth2/code/azure' (redirected from 'http://localhost:4200/account') from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1
anyone know how to call localhost:8080(docs.microsoft.com/en-us/azure/developer/java/spring-framework/…) from angular.shraban rana
You can't. These are different origins on AzureAD. You could have a route in your apps that redirects/serves up the UI as a workaroundDarren Forsythe
How to call spring azure auth login api((docs.microsoft.com/en-us/azure/developer/java/spring-framework/…) . from UIshraban rana
Any one have any idea of calling angular localhost:4200 to localhost:8080 which is spring azure Ad . (spring is configured as per document : docs.microsoft.com/en-us/azure/developer/java/spring-framework/…)) . Direct hit localhosy:8080 works fine. But from 4200 port. Not working. Any one knows. Please make comment. Urgentshraban rana
Anyone knows. java developer. SSO is not new. anyone have implemented. please commentshraban rana

1 Answers

0
votes

The issue that you might be facing is that spring security is not letting through the pre-flight checkup requests and failing them.

Add

configuration.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept","Authorization"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));

and In Angular try adding Proxying to a backend server