programing

스프링 OAuth redirect_uri가 https를 사용하지 않음

showcode 2023. 3. 31. 23:02
반응형

스프링 OAuth redirect_uri가 https를 사용하지 않음

SSO 통합의 일종으로 Spring Security OAuth가 포함된 Spring Boot 1.3.0 애플리케이션을 사용하고 있습니다.

문제는 애플리케이션이 SSL을 강제 적용하는 로드 밸런서(F5) 뒤에 비표준 포트가 있는 비SSL 환경에서 실행되고 있으며 OAuth 공급자는 모든 리디렉션 URL을 https로 등록해야 하지만 Spring OAuth 클라이언트(@Enable로 자동 구성됨)가 필요합니다.OAuthSo)는 다음 URL을 가진 OAuth 공급자로만 리디렉션됩니다.

https://[provider_host]/oauth/auth?client_id=[redact]&redirect_uri=https://[application_host]/login&response_type=code&scope=[redact]&state=IpMYTe

return redirect_uri는 http로 생성됩니다.F5는 돌아오는 길에 강제로 https로 하는데 OAuth 공급자는 SSL 이외의 리다이렉트 URI를 허용하지 않습니다.어떻게 하면 좋을까요?

Spring Data JPA 컨트롤러를 제외하고 앱 전체입니다.

AppConfig.java

@SpringBootApplication(exclude = { HibernateJpaAutoConfiguration.class })
@EnableJpaRepositories
public class AppConfig extends SpringBootServletInitializer {

    public static void main(final String... args) {
        SpringApplication.run(AppConfig.class, args);
    }

    @Autowired
    public DataSource dataSource;

    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryInfo() {
        final LocalContainerEntityManagerFactoryBean fac = new LocalContainerEntityManagerFactoryBean();
        fac.setDataSource(dataSource);
        fac.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        fac.setPackagesToScan("[redact]");

        final Properties props = new Properties();
        props.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
        props.put("hibernate.show_sql", "true");
        props.put("hibernate.format_sql", "true");
        fac.setJpaProperties(props);

        return fac;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager getTransactionManager() {
        final JpaTransactionManager transactMngr = new JpaTransactionManager();
        transactMngr.setEntityManagerFactory(getEntityManagerFactoryInfo().getObject());
        return transactMngr;
    }

}

SecurityConfig.java

@Configuration
@EnableOAuth2Sso
public class SecurityConfig {

}

application.properties

server.port=9916
server.contextPath=

server.use-forward-headers=true

security.oauth2.client.clientId=[redact]
security.oauth2.client.clientSecret=[redact]
security.oauth2.client.scope=[redact]
security.oauth2.client.accessTokenUri=https://[provider_host]/oauth/token
security.oauth2.client.userAuthorizationUri=https://[provider_host]/oauth/authorize
security.oauth2.resource.userInfoUri=https://[provider_host]/oauth/me
security.oauth2.resource.preferTokenInfo=false

logging.level.org.springframework=TRACE

컨피규레이션클래스를 수동으로 조사한 결과, 다음의 항목을 찾아 추가할 수 있었습니다.그게 효과가 있었습니다.

security.oauth2.client.pre-established-redirect-uri=https://[application_host]/login
security.oauth2.client.registered-redirect-uri=https://[application_host]/login
security.oauth2.client.use-current-uri=false

HTTPS 리다이렉트 URL을 강제적으로 실행하는 문제를 해결할 수 있는 더 좋은 방법이 없다고 생각합니다만, 이 수정은 효과가 있었습니다.

어플리케이션의 이해도를 확인할 필요가 있을 수 있습니다.x-forwarded헤더를 로드 밸런서에서 가져옵니다.

이것을 내 안에 넣는 것은application.ymlAWS ELB의 배후에 있는 어플리케이션과 같은 문제를 해결했습니다.

server:
  tomcat:
    remote-ip-header: x-forwarded-for
    protocol-header: x-forwarded-proto

편집: 이것은 보다 일반적인 구성으로 심플화할 수 있습니다.

server:
  use-forward-headers: true

Apache Tomcat 사용RemoteIpValveserver.xml(위)AccessLogValve):

    <Valve className="org.apache.catalina.valves.RemoteIpValve" 
        protocolHeader="X-Forwarded-Proto" />

https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html 도 참조해 주세요.

위의 답변은 저에게 맞지 않았기 때문에 최신 봄 버전을 사용하는 사람들을 위한 답변입니다.Spring Boot 2.3.5를 사용하고 있습니다.풀어주다.

같은 문제가 있었습니다만, Azure AD를 oauth2 인증에 사용하고 있습니다.어플리케이션이 리버스 프록시 뒤에서 실행되고 있는 리다이렉트 URI가 https가 아닌 http를 사용하고 있습니다.

문서 https://docs.spring.io/spring-security/site/docs/5.2.x/reference/html/oauth2.html#oauth2Client-auth-code-redirect-uri을 읽고 application.properties 파일에 다음 행을 추가했는데, 그것이 나에게 효과가 있었습니다.

spring.security.oauth2.client.registration.azure.redirect-uri=https://{baseHost}{basePort}{basePath}/login/oauth2/code/azure

당신이 oauth의 사용을 언급했기 때문에, 이것은 누군가가 조작의 흐름을 이해하는 데 도움이 될 것이라고 생각합니다.이 답변은 NGINX 등의 역프록시를 사용하는 경우에만 적용됩니다.

문제의 원인  

spring 부트애플리케이션이 http://localhost:8080 주소의 서버에서 실행되고 있습니다.이것이 모든 스프링 부트 앱이 호스트에 대해 알고 있는 것입니다.facebook(또는 기타 oauth 클라이언트) 오류 페이지에서 리다이렉트 URL을 체크하면 이 동작을 검사할 수 있습니다.https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250),link&redirect_url=http%3A%2F%2Flocalhost%2Flogin%2Ffacebook과 같이 표시됩니다.

redirect_url이 잘못되었음을 확인합니다.

따라서 이 주소로 호스팅된다는 것을 애플리케이션에 알려야 합니다.

퀵픽스

Facebook OAuth(또는 다른 oAuth 프로바이더)만을 수정하는 경우 클라이언트에 다음 행을 추가하면 수정됩니다.

facebook:
  client:
     preEstablishedRedirectUri: https://yourdomain.com/
     useCurrentUri: false

다만, 이것은, 당면한 문제를 해결할 뿐입니다(또한 유연성이 없습니다).그러나 휴대할 수 있는 보다 구체적인 솔루션이 필요한 경우 역방향 프록시로 해결해야 합니다.

앱의 nginx 구성을 열고 다음과 같이 변경하세요.

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Will add the user's ip to the request, some apps need this
        proxy_set_header X-Forwarded-Proto $scheme; # will forward the protocole i.e. http, https
        proxy_set_header X-Forwarded-Port $server_port; # Will forward the port 
        proxy_set_header Host $host;                    # !Important will forward the host address
        proxy_pass http://localhost:8080/;
}

이제 nginx가 스프링 부트 앱에 숨겨져 있던 정보를 전송합니다.그러나 스프링 앱은 이 정보를 사용하지 않습니다.이러한 정보를 사용하도록 하려면 application.yml에 다음 행을 추가합니다.

server.use-forward-headers = true

같은 네트워크의 다른 노드에 리버스 프록시가 있는 경우는, 다음과 같이 리버스 프록시 서버의 IP 를 설정할 수 있습니다.(IP로 대체)

server.tomcat.internal-proxies=192\.65\.210\.55

저도 같은 문제가 있었어요.다음 2개의 파라미터를 추가하여 redirect_uri에 HTTPS를 강제 적용합니다.

preEstablishedRedirectUri: https://...
useCurrentUri: false

동작: "redirect_uri"는 현재 HTTPS를 사용하고 있습니다.

하면 '어울리지 않다'를 써야 할 도 있어요.spring.oauth2.client.access-token-uri

설정 파라미터가 1.3.0 이후에 변경되었습니다.M1

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.3.0-M1-Configuration-Changelog

언급URL : https://stackoverflow.com/questions/33812471/spring-oauth-redirect-uri-not-using-https

반응형