如何在ID Token中包含SID以实现Spring OAuth Server用户登出?
在Spring OAuth Server中为ID Token添加sid声明的解决方案
要解决登出时缺少SID的问题,你需要显式配置让Spring OAuth Server将sid声明注入到ID Token中——默认情况下该声明不会自动包含,具体步骤如下:
自定义ID Token生成逻辑,添加sid声明
创建OAuth2TokenCustomizerBean,从认证上下文里提取会话ID并写入ID Token的声明中:@Bean public OAuth2TokenCustomizer<JwtEncodingContext> idTokenSidCustomizer() { return context -> { // 仅对ID Token进行处理 if (OAuth2TokenType.ID_TOKEN.equals(context.getTokenType())) { Authentication auth = context.getPrincipal(); String sid = null; // 从SessionAuthenticationToken中获取会话ID if (auth instanceof SessionAuthenticationToken) { sid = ((SessionAuthenticationToken) auth).getSessionId(); } // 也可以直接从SecurityContext获取会话ID // sid = SecurityContextHolder.getContext().getSessionId(); if (sid != null) { context.getClaims().claim("sid", sid); } } }; }确保客户端认证请求包含
openidscope
客户端必须请求openidscope才会触发ID Token的生成,检查你的客户端配置:@Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient client = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("your-client-id") .clientSecret("{noop}your-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("your-redirect-uri") .scope("openid") // 必须包含该scope .scope("profile") .build(); return new InMemoryRegisteredClientRepository(client); }验证配置生效
发起认证流程获取ID Token后,用JWT解码工具解析Token,确认sid声明已存在。此时登出时即可使用该参数完成会话关联失效。
内容的提问来源于stack exchange,提问作者Ramon10
相关产品推荐
相关产品推荐

