2

我正在使用具有 OAuth2 单点登录的 spring-boot 应用程序(正在开发中,但已经在工作)。

我将会话存储从 Tomcat 更改为 Redis。

问题

当我ClassCastException尝试从SecurityContextHolder.

将用户对象存储到UsernamePasswordAuthenticationToken

@Service
@Transactional
public class MyTokenService implements ResourceServerTokenServices {

  @Setter
  private OAuth2RestOperations restTemplate;

  @Autowired
  ResourceServerProperties sso;

  @Override
  public OAuth2Authentication loadAuthentication(String accessToken)
      throws AuthenticationException, InvalidTokenException {

    // get from http://some-auth-provider/me
    MyUser myUser = getMyInfo();

    // persist to mysql
    UserEntity user = save(myUser);

    OAuth2Request request =
        new OAuth2Request(null, sso.getClientId(), null, true, null, null, null, null, null);

    // org.springframework.boot.devtools.restart.classloader.RestartClassLoader@3d66ad6e
    logger.info(user.getClass().getClassLoader().toString());

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(user.getId(), "N/A", user.getAuthorities());
    token.setDetails(user);

    return new OAuth2Authentication(request, token);
  }

  @Override
  public OAuth2AccessToken readAccessToken(String accessToken) {
    throw new UnsupportedOperationException("Not supported: read access token");
  }
}

认证后的会话

127.0.0.1:6379> keys *
1) "spring:session:expirations:1445309400000"
2) "spring:session:sessions:3447d160-5f41-49c9-abf9-2bf0ef2e6bc2"
127.0.0.1:6379> hkeys spring:session:sessions:3447d160-5f41-49c9-abf9-2bf0ef2e6bc2
1) "sessionAttr:SPRING_SECURITY_SAVED_REQUEST"
2) "sessionAttr:org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN"
3) "lastAccessedTime"
4) "maxInactiveInterval"
5) "sessionAttr:SPRING_SECURITY_LAST_EXCEPTION"
6) "sessionAttr:SPRING_SECURITY_CONTEXT"
7) "creationTime"
127.0.0.1:6379> type spring:session:sessions:3447d160-5f41-49c9-abf9-2bf0ef2e6bc2:sessionAttr:SPRING_SECURITY_CONTEXT
none

检索用户对象(经过身份验证后)

public UserEntity getMyInfo() {

  OAuth2Authentication oAuth2Authentication =
      (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();

  Long userId = (Long) oAuth2Authentication.getPrincipal();

  UsernamePasswordAuthenticationToken userAuthentication =
        (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();

  try {
    // sun.misc.Launcher$AppClassLoader@14dad5dc
    logger.info(userAuthentication.getDetails().getClass().getClassLoader().toString());

    return (UserEntity) userAuthentication.getDetails(); 
  } catch (Exception e) {
    // fixme ClassCastException

    // workaround
    return userRepository.accountDetail(userId);
  }
}

我调试userAuthentication对象并确认userAuthentication.details拥有 MyUser 对象。所以ClassCastException发生在将 UserEntity 转换为 UserEntity 时,但为什么呢?

我可以正确获取主体(=UserEntity.id)。

有没有人有任何解决方案?

以下是当前配置的一部分。

依赖项

springBootVersion = '1.3.0.RC1'

compile("org.springframework.boot:spring-boot-starter-redis")
compile("org.springframework.session:spring-session")
compile("com.github.kstyrc:embedded-redis:0.6")

Redis 配置

@Configuration
@EnableRedisHttpSession
public class RedisConfig {

  private static RedisServer redisServer;

  @Profile({"local", "unit"})
  @Bean
  public RedisConnectionFactory connectionFactory() throws IOException {

    RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
      .override(OS.MAC_OS_X, Architecture.x86_64, "/path/to/redis/3.0.2/redis-server");

    redisServer = new RedisServerBuilder()
      .redisExecProvider(customProvider)
      .port(Protocol.DEFAULT_PORT)
      .build();

    redisServer.start();

    return new JedisConnectionFactory();
  }

  @Profile({"local", "unit"})
  @PreDestroy
  public void destroy() {

    if (redisServer != null) {
      redisServer.stop();
    }
  }

  @Bean
  @ConditionalOnMissingBean(RequestContextFilter.class)
  public RequestContextFilter requestContextFilter() {

    return new RequestContextFilter();
  }

  @Bean
  public FilterRegistrationBean requestContextFilterChainRegistration(
  @Qualifier("requestContextFilter") Filter securityFilter) {

    FilterRegistrationBean registration = new FilterRegistrationBean(securityFilter);
    registration.setOrder(SessionRepositoryFilter.DEFAULT_ORDER + 1);
    registration.setName("requestContextFilter");

    return registration;
  }

OAuth2 Sso 配置

@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
public class OAuth2Config extends WebSecurityConfigurerAdapter {

  @Autowired
  ResourceServerProperties sso;

  @Autowired
  @Qualifier("userInfoRestTemplate")
  private OAuth2RestOperations restTemplate;

  @Primary
  @Bean
  public ResourceServerTokenServices userInfoTokenServices() {

    MyTokenService tokenService = new MyTokenService();
    tokenService.setRestTemplate(restTemplate);

    return tokenService;
  }

  // ...
}

类似问题

使用 spring-session 和 spring-cloud-security 时,OAuth2ClientContext (spring-security-oauth2) 不会保留在 Redis 中

我按照上面的答案更改过滤器顺序(在 RedisConfig.java 中),但它不起作用。

我当前的过滤顺序如下。

o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'metricFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'springSessionRepositoryFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'OAuth2ClientContextFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'springSecurityFilterChain' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'webRequestLoggingFilter' to: [/*]
o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'applicationContextIdFilter' to: [/*]

更新代码

ClassCastException 的原因是 ClassLoader 的不匹配。

org.springframework.boot.devtools.restart.classloader.RestartClassLoadersun.misc.Launcher$AppClassLoader

但我不知道如何解决这个问题,一如既往。

解决了!

我在下面更改了过滤器顺序,它可以工作。

  1. 请求上下文过滤器
  2. oAuth2ClientContextFilter
  3. springSessionRepositoryFilter
4

0 回答 0