OAuth2 + Spring Boot 2-ZuulGateway中带有授权服务器的ResourceServer

时间:2019-05-04 09:29:51

标签: spring spring-boot spring-security jwt spring-security-oauth2

我正在尝试使用Spring Boot 2 + Netflix OSS进行OAuth 2 + JWT集成。请求访问令牌时,我在充当资源服务器的Zuul Gateway中收到以下错误。

2019-05-04 14:41:29.157调试23272 --- [nio-8765-exec-2] o.s.s.w.a.ExceptionTranslationFilter:发生认证异常;重定向到身份验证入口点 org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:在SecurityContext中找不到身份验证对象

有人可以帮我告诉我代码中我缺少什么吗?

Zuul网关+资源服务器

@Configuration
@EnableResourceServer
@Order(value = 0)
@EnableOAuth2Sso
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/oauth/token/**").permitAll()
            //.antMatchers("/login/**,/oauth/**").permitAll()
            .antMatchers("/trips/**").hasAnyRole("CLIENT", "USER", "ANONYMOUS")
            .and().csrf().disable()
            .anonymous().disable();

    }
}

application.yml

logging:
  level:
    org.springframework: DEBUG

server:
  port: 8765

spring:
  application:
    name: gateway


# Map path to auth service
zuul:
  routes:
    trips:
      path: /trips/**
      url: http://localhost:1000/api/trips
    rides:
      path: /rides/**
      url: http://localhost:1000/api/rides
    mauth:
      path: /oauth/**
      url: http://localhost:1000/oauth



#OAuth Configurations
security:
  oauth2:
    client:
      #access-token-uri: https://auth/login
      #user-authorization-uri: /auth/oauth/authorize
      accessTokenUri: http://localhost:1000/oauth/authorize
      userAuthorizationUri: http://localhost:1000/oauth/token
      client-id: sapepool
      client-secret: sapepool
    resource:
      jwt:
        key-uri: http://localhost:1000/oauth/token_key
        #key-value:

授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        @Qualifier("customUserDetailsService")
        private UserDetailsService userDetailsService;

        /**
         * Token store.
         *
         * @return the token store
         */
        /*@Bean
        public DatastoreTokenStore tokenStore() {
            return new DatastoreTokenStore(datastoreDataSource);
        }*/
        @Bean
        public TokenStore tokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }

        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setKeyPair(new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "password".toCharArray()).getKeyPair("jwt"));
            converter.setSigningKey("123");
            converter.setVerifierKey("123");
            return converter;
        }

        /**
         * 
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

            endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService)
                    .tokenStore(tokenStore())//.tokenServices(tokenServices())
                    .tokenEnhancer(jwtAccessTokenConverter())
                    .accessTokenConverter(jwtAccessTokenConverter())
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        }

         /**
         * Authorization server security Configuration.
         *
         * @param oauthServer
         *            the oauth server
         * @throws Exception
         *             the exception
         */
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                .withClient("sapepool")
                .secret("{noop}sapepool")
                //.secret("sapepool")
                .authorizedGrantTypes("client_credentials", "password","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT", "ROLE_ANONYMOUS")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(5000)
                .refreshTokenValiditySeconds(50000);
                //.resourceIds("oauth2-resource") - isAutoApprove()
        }
    }

授权服务器-Web安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);


    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

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

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/oauth/token/**").permitAll()
            .anyRequest().permitAll()
            //.antMatchers("*/oauth/**").permitAll()
            //.antMatchers("/**").permitAll()
            .and().csrf().disable();
            //.anonymous().disable();

        /*
         * http.csrf().disable().exceptionHandling() //.authenticationEntryPoint( //
         * (request, response, authException) ->
         * response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
         * .and().authorizeRequests().antMatchers("/**").authenticated().and().httpBasic
         * ();
         */
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}

0 个答案:

没有答案