当前位置: 首页 > 知识库问答 >
问题:

Spring Cloud Zuul-使用生成的jwt令牌时,授权服务器拒绝访问

林龙野
2023-03-14

我试图实现微服务架构后端api服务器的使用Spring Cloud Dalston.SR4将被移动/网络应用程序使用。

API网关

下面是网关微服务的配置

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

}
@Configuration
@EnableWebSecurity
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() //
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //
                .and().authorizeRequests() //
                .antMatchers("/login", "/uaa/**").permitAll() //
                .anyRequest().authenticated();
    }

}

应用yml

zuul:
  ignoredServices: '*'
  routes:
    user-service:
      path: /users/**
      service-id: user-service
      sensitive-headers: 
    uaa:
      path: /uaa/**
      strip-prefix: false
      url: ${auth-server.uri}/
      sensitive-headers: 
security:
  user:
    password: none
  basic:
    enabled: false
  oauth2:
    client:
      client-id: client
      client-secret: secret
      scope: openid
      access-token-uri: ${auth-server.uri}/uaa/oauth/token
      user-authorization-uri: ${auth-server.uri}/uaa/oauth/authorize
    resource:
      jwt:
        key-value: |
          -----BEGIN PUBLIC KEY-----
          MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhVny3DfQqdvQaPj6SJiiFfPRGH/5k3OiAXTCsmpKnL/GVKZpfFjT3LhN7xoj0DzJLTCOE94eOjIHipFzxrL00kBCZJ3HOornKDpTh17yPuqJI6DNmvJaRBbc3SVQsO0vndnDAeOBiv4euGHH97sPZYFqhmwM35PboqxeWaHrfgWcA5F8VFTp+HDPr26G4sv/UqkR1LsfRoD4gzNJswi00eWcNjeoEzy71023VECQYDytUg/wVqWOJnShWOJnCBnuzmjrtOCg6O6ecdHhVaiRI0//ZR71x2oDW5pe+kgVhhM29TH8SVRjbAFh35obN6ppcF3A7PFLf+euZTsmXMaahQIDAQAB
          -----END PUBLIC KEY-----

身份验证服务

@SpringBootApplication
@RestController
@EnableEurekaClient
@EnableResourceServer
public class AuthServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthServiceApplication.class, args);
    }

    @GetMapping("/user")
    public Principal getUser(Principal user) {
        return user;
    }

}
@Configuration
@EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"), "keypass".toCharArray());
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("keystore"));
        return converter;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory() //
                .withClient("client") //
                .secret("secret") //
                .authorizedGrantTypes("authorization_code", "refresh_token", "password") //
                .scopes("openid") //
                .accessTokenValiditySeconds(60 * 60 * 24 * 1);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

}
@Configuration
@Order(-20)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().disable()//
                .csrf().disable() //
                .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access") //
                .and().authorizeRequests().anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user1").password("pass1").roles("USER");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

通过这个设置,我能够从uaa/oauth/token服务生成访问令牌。我可以使用相同的令牌调用uaa/用户服务endpoint,甚至可以直接调用其他微服务(比如用户服务)。

但是当我使用前面生成的令牌通过网关调用用户服务时,我从授权服务器获得了一个访问拒绝错误。

要求—http://localhost:8080/users/test

具有头授权:承载

但来自身份验证服务器的响应被拒绝访问

2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 5 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.s.DefaultSavedRequest            : queryString: arg1=client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=GwhNJf; arg2=client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I (property not equals)
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 6 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 7 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 0F2BD608483668F10E9AD88B507858E9; Granted Authorities: ROLE_ANONYMOUS'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.security.web.FilterChainProxy        : /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /oauth/authorize?client_id=client&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid&state=6AYJ3I; Attributes: [authenticated]
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 0F2BD608483668F10E9AD88B507858E9; Granted Authorities: ROLE_ANONYMOUS
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@21c53585, returned: -1
2017-10-23 12:38:41.470 DEBUG 4320 --- [trace=,span=] [nio-9999-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)

共有1个答案

翟鹏
2023-03-14

@EnableOAuth2Sso使用SSO保护所有网关URL。我相信您需要禁用通向下游微服务的路由上的身份验证,以便承载令牌可以到达它们。

尝试添加/user/**到网关上的permitAll()匹配器:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and().authorizeRequests()
      .antMatchers("/users/**", /login", "/uaa/**").permitAll();
}
 类似资料:
  • 我们正在使用Spring引导作为后端,仅为auth和生成jwt令牌的其余部分在hasura中处理。 我面临正确生成JWT的问题。 这是生成jwt令牌作为 但它hasura返回无效的签名。在哪里作为在节点 jwt从节点 使用相同的密钥和算法工作得非常好。对于节点,我使用了jsonwebtoken库。

  • 我目前正在学习OAuth 2.0和OpenID Connect,我对授权服务器和访问令牌有疑问。规范将授权服务器定义为: 服务器在成功验证资源所有者并获得授权后向客户端发放访问令牌。 因此,据我所知,客户端将用户重定向到授权服务器,用户在授权服务器上进行身份验证,授权服务器向客户端发出访问令牌。 现在有一件事发生了,直到现在我才明白。有两种可能的方法来理解这一点,我正在努力找到正确的方法: > 授

  • 寻求有关如何进行微服务授权的建议。 我使用spring/spring boot来提供所有的微服务 在使用JWT令牌到达实际微服务之前,我可以通过Spring Cloud网关进行身份验证,但是在授权方面,我不确定如何做到这一点。 我想在内部处理business microservice中每个endpoint的授权。 有没有办法将JWT令牌传递给微服务,或者我需要调用authserver来获取用户中的

  • 我对spring security&oauth2相当陌生。作为学习的一部分,我试图设置一个OAuth2授权服务器,并保护RESTendpoint免受未经授权的访问。 代码 资源服务器 ProductController.java 未经授权API可以正常工作 如果我们只使用权限(@preauthorize(“hasauthorize('...')”))进行授权,它可以正常工作 作用域在到达oauth

  • 我有一个Web api终端,它给我JWT令牌。它不是一个完全授权的服务器。它只是可以生成一个JWT令牌。 现在我有另一个用 aspnet 核心编写的 Web 应用程序。其中在启动中.cs我添加了以下行,以便我可以使用收到的 JWT 令牌进行授权 我也有一个登录表单(在web应用程序中),用户输入用户名和密码,我发送到web api并获得令牌。为了保护web应用程序中的任何控制器,我只使用了[Aut

  • 我试图按照指南为YAHOO DSP API生成Oauth认证令牌。 Base64编码是一种将二进制数据编码为文本的方式,这样可以轻松无误地通过网络传输。 在此步骤中,您将获取YDN控制台为您生成的客户端ID和客户端密码,并使用base64协议对它们进行编码。你可以使用base64encode.org这样的在线编码服务。 无论您使用哪种服务,请确保CLIENT_ID和CLIENT_SECRET键上不