spring-security Spring Security OAuth 2 -授权服务器从0.1.0更新为0.1.1 / 0.1.2,导致示例项目无法工作

polhcujo  于 2022-11-11  发布在  Spring
关注(0)|答案(3)|浏览(105)

我想使用新的Spring Security Authorization Server为我的Web服务实现OAuth2
https://www.baeldung.com/spring-security-oauth-auth-server处给出了一个例子,分离

  • 授权服务器
  • 资源服务器
  • 委托方

该代码可在https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-authorization-server中找到
这三个Maven项目在给定版本中正常工作,当Web浏览器中的客户端访问http://localhost:8080/articles时,输出正确

["Article 1","Article 2","Article 3"]

我尝试将Authorization Server项目更新为0.1.1,但是尽管它可以编译并启动,但当客户端访问http://localhost:8080/articles时,我得到

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Aug 07 15:57:26 CEST 2021
There was an unexpected error (type=None, status=999).

我想这是因为我必须更新所有三个项目中的其他版本,到Spring Boot 2.5.3OpenJDK 16,但同样的错误。
我更新为0.1.2并将日志级别更改为DEBUG,启动授权服务器项目时会出现以下内容:

...
2021-08-09 17:54:45.876 DEBUG 16256 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat'
    2021-08-09 17:54:46.015 DEBUG 16256 --- [           main] o.a.catalina.core.AprLifecycleListener   : The Apache Tomcat Native library could not be found using names [tcnative-1, libtcnative-1] on the java.library.path [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]. The errors reported were [Can't load library: /home/myself/PROJECTs/SPRING/spring-authorization-server/bin/libtcnative-1.so, Can't load library: /home/myself/PROJECTs/SPRING/spring-authorization-server/bin/liblibtcnative-1.so, no tcnative-1 in java.library.path: /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib, no libtcnative-1 in java.library.path: /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]

    org.apache.tomcat.jni.LibraryNotFoundError: Can't load library: /home/myself/PROJECTs/SPRING/spring-authorization-server/bin/libtcnative-1.so, Can't load library: /home/myself/PROJECTs/SPRING/spring-authorization-server/bin/liblibtcnative-1.so, no tcnative-1 in java.library.path: /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib, no libtcnative-1 in java.library.path: /usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib
        at org.apache.tomcat.jni.Library.<init>(Library.java:101) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
        at org.apache.tomcat.jni.Library.initialize(Library.java:211) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
        at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:192) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
        at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:101) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getDefaultLifecycleListeners(TomcatServletWebServerFactory.java:173) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.<init>(TomcatServletWebServerFactory.java:120) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat.tomcatServletWebServerFactory(ServletWebServerFactoryConfiguration.java:76) ~[spring-boot-autoconfigure-2.5.3.jar:2.5.3]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.9.jar:5.3.9]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:217) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.9.jar:5.3.9]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar:2.5.3]
        at com.baeldung.OAuth2AuthorizationServerApplication.main(OAuth2AuthorizationServerApplication.java:10) ~[classes/:na]
...

0.1.1看起来也是这样
我的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.baeldung</groupId>
    <artifactId>spring-authorization-server</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.experimental</groupId>
            <artifactId>spring-security-oauth2-authorization-server</artifactId>
            <version>0.1.2</version>
        </dependency>
    </dependencies>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>16</java.version>
    </properties>
</project>

仅更改pom.xml、0.1.0或0.1.1或0.1.2中的授权服务器版本会产生相同的异常。
Baeldung的示例项目只在0.1.0中运行(从localhost:8080/articles中交付文章),但在0.1.1和0.1.2中,我得到了所描述的Whitelable错误页。

ujv3wf0j

ujv3wf0j1#

首先,我建议您检查一下samples in the spring-authorization-server project本身(例如,请参见这一行),这将确保您跟上项目中发生的快速变化,因为Web上的那些教程往往很快就会过时。
第二,我相信调试中的第二个错误与此问题无关,所以这似乎是一个本地设置问题,但我不是100%肯定。
第三,由于#243,第一个错误发生在SAS的较新版本上。更改包括合并OAuth 2.1第9.7.1节中的建议,其中规定:
虽然使用localhost(即“http://localhost:{port}/{path}”)的重定向URI的功能类似于第10.3.3节中描述的环回IP重定向,但不建议使用“localhost”。使用环回IP文字而不是“localhost”指定重定向URI可避免无意中侦听环回接口以外的网络接口。它还不易受到客户端防火墙和用户设备上配置错误的主机名解析的影响。
当重定向URI的主机为localhost时,此错误仅在重定向回客户端应用程序时出现。如果您在授权服务器中启用跟踪日志记录(例如logging.level.org.springframework.security=trace),您将看到一个成功的身份验证,然后重定向到一个错误页,类似于:

...
2021-08-10 11:10:41.596 DEBUG 90071 --- [io-9000-exec-10] w.a.UsernamePasswordAuthenticationFilter : Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_PILOT]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=3786957448CCBB82DAE6AB29DBCA5D2C], Granted Authorities=[ROLE_USER]]
2021-08-10 11:10:41.596 DEBUG 90071 --- [io-9000-exec-10] o.s.s.web.DefaultRedirectStrategy        : Redirecting to http://auth-server:9000/error?response_type=code&client_id=messaging-client&scope=openid&state=Vg-fUjLSdOjAG_4Y9LcjcxxYTGhd33Trbaclp92XoDQ%3D&redirect_uri=http://localhost:8080/login/oauth2/code/messaging-client&nonce=s8hJD_zDopreLImNeRwQ3fslL4yFNySjbt6MiYK1mPw
...

这说明在流的早期发生了一些事情,我们只是在此时遇到了症状。如果在登录之前查看日志的更高部分,您将看到类似以下的内容:

...
2021-08-10 11:10:37.444 TRACE 90071 --- [nio-9000-exec-8] o.s.security.web.FilterChainProxy        : Invoking OAuth2AuthorizationEndpointFilter (6/24)
2021-08-10 11:10:37.444 TRACE 90071 --- [nio-9000-exec-8] o.s.s.authentication.ProviderManager     : Authenticating request with OAuth2AuthorizationCodeRequestAuthenticationProvider (1/10)
2021-08-10 11:10:37.445 TRACE 90071 --- [nio-9000-exec-8] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]
2021-08-10 11:10:37.445 DEBUG 90071 --- [nio-9000-exec-8] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-08-10 11:10:37.445 DEBUG 90071 --- [nio-9000-exec-8] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-08-10 11:10:37.445 DEBUG 90071 --- [nio-9000-exec-8] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2021-08-10 11:10:37.447 TRACE 90071 --- [nio-9000-exec-8] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer$$Lambda$603/0x000000080041a040@4dd90166, Filters=[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@52227eb2, org.springframework.security.web.context.SecurityContextPersistenceFilter@21263314, org.springframework.security.web.header.HeaderWriterFilter@4d84049a, org.springframework.security.web.csrf.CsrfFilter@1d8b0500, org.springframework.security.web.authentication.logout.LogoutFilter@6413d7e7, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter@32d5279, org.springframework.security.oauth2.server.authorization.oidc.web.OidcProviderConfigurationEndpointFilter@fe87ddd, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServerMetadataEndpointFilter@448b808a, org.springframework.security.oauth2.server.authorization.web.NimbusJwkSetEndpointFilter@ebda593, org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter@22d322f5, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4337afd, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@d16be4f, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@5ad1904f, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter@60e06f7d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4a92c6a9, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@64c781a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@a146b11, org.springframework.security.web.session.SessionManagementFilter@642857e0, org.springframework.security.web.access.ExceptionTranslationFilter@30c3ae63, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@550e9be6, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter@32ec9c90, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenIntrospectionEndpointFilter@456bcb74, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter@3b332962, org.springframework.security.oauth2.server.authorization.oidc.web.OidcClientRegistrationEndpointFilter@58a2d9f9]] (1/2)
2021-08-10 11:10:37.447 TRACE 90071 --- [nio-9000-exec-8] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1b01a0d, org.springframework.security.web.context.SecurityContextPersistenceFilter@91f565d, org.springframework.security.web.header.HeaderWriterFilter@67b355c8, org.springframework.security.web.csrf.CsrfFilter@79f90a3a, org.springframework.security.web.authentication.logout.LogoutFilter@414f87a9, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@6e31d989, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1ddc6db2, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@2ed71727, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@46e3559f, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3b83459e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5261ec9, org.springframework.security.web.session.SessionManagementFilter@388623ad, org.springframework.security.web.access.ExceptionTranslationFilter@22bdb1d0, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@416d56f2]] (2/2)
2021-08-10 11:10:37.447 DEBUG 90071 --- [nio-9000-exec-8] o.s.security.web.FilterChainProxy        : Securing GET /error?response_type=code&client_id=messaging-client&scope=openid&state=Vg-fUjLSdOjAG_4Y9LcjcxxYTGhd33Trbaclp92XoDQ%3D&redirect_uri=http://localhost:8080/login/oauth2/code/messaging-client&nonce=s8hJD_zDopreLImNeRwQ3fslL4yFNySjbt6MiYK1mPw
...

因此,错误实际上发生在OAuth2AuthorizationEndpointFilter中,验证后,错误重定向保存为目标URL,然后我们被重定向到/login,验证后,重定向回/error,这将生成一个白标签错误页面。
短期的解决方法是确保您的客户端应用程序使用127.0.0.1,而不是localhost,包括更改授权服务器中的重定向URI(参见示例)。但是,如果您忘记并在http://localhost:8080启动浏览器,您仍然会收到此错误。您现在可以在客户端应用程序中使用如下过滤器来解决此问题:

/**
 * This filter ensures that the loopback IP <code>127.0.0.1</code> is used to access the
 * application so that the sample works correctly, due to the fact that redirect URIs with
 * "localhost" are rejected by the Spring Authorization Server, because the OAuth 2.1
 * draft specification states:
 *
 * <pre>
 *     While redirect URIs using localhost (i.e.,
 *     "http://localhost:{port}/{path}") function similarly to loopback IP
 *     redirects described in Section 10.3.3, the use of "localhost" is NOT
 *     RECOMMENDED.
 * </pre>
 *
 * @see <a href=
 * "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-01#section-9.7.1">Loopback Redirect
 * Considerations in Native Apps</a>
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LoopbackIpRedirectFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getServerName().equals("localhost")) {
            UriComponents uri = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
                    .host("127.0.0.1").build();
            response.sendRedirect(uri.toUriString());
            return;
        }
        filterChain.doFilter(request, response);
    }

}

我鼓励您通过open an issue请求改进此错误的处理方式。如果您感兴趣,我们很乐意与您讨论此问题,并让您参与到项目中来帮助解决此问题。

r6hnlfcb

r6hnlfcb2#

我也遇到了同样的问题,经过四五天的努力,我找到了解决办法。
我刚刚在etc/hosts文件中添加了以下条目
127.0.0.1 认证服务器
解决了这个问题

v440hwme

v440hwme3#

我有同样的错误比你的第二个,关于Spring不能加载2库的apache tomcat。我知道你要求一个解决方案,但我会告诉你我希望有人告诉我。

**这只是来自SpringBoot的DEBUG级别日志。它不是ERROR或WARNING日志。这没关系。**世界上所有的spingboot应用程序可能都有相同的日志。

你已经激活了整个应用程序的调试日志,甚至在库中。我不建议默认情况下这样做,因为它会记录太多。
仅在应用程序的主包上启用DEBUG模式。然后,当需要调试特定库包时,仅在其上激活DEBUG模式。
例如,如果您需要查看mongodb-driver执行的请求,那么您的application.yml应该如下所示:

logging:
  level:
    root: INFO
    mymainpackage: DEBUG
    org:
      mongodb: DEBUG

相关问题