Spring Security中自定义oauth_access_token表字段无法赋值问题求助
解决建议
同步实体类与数据库字段
如果是自定义的AccessToken实体类,确保已添加新增字段及对应的getter/setter方法;若使用Spring Security OAuth默认的DefaultOAuth2AccessToken,需扩展该类并添加新字段,同时通过@Column注解明确数据库字段映射(比如数据库字段是custom_field,实体属性要加@Column(name = "custom_field")),避免因驼峰/下划线命名不匹配导致赋值失败。修改TokenStore的SQL操作逻辑
若使用JdbcTokenStore,默认的插入、更新SQL并未包含自定义字段,需自定义JdbcTokenStore并重写相关方法:@Override protected void insertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { String sql = "INSERT INTO oauth_access_token (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token, custom_field) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; // 从token扩展属性中获取自定义字段值 String customValue = (String) token.getAdditionalInformation().get("customField"); jdbcTemplate.update(sql, extractTokenKey(token.getValue()), serializeAccessToken(token), authenticationIdGenerator.extractKey(authentication), authentication.getName(), authentication.getOAuth2Request().getClientId(), serializeAuthentication(authentication), token.getRefreshToken() != null ? extractTokenKey(token.getRefreshToken().getValue()) : null, customValue); }同理重写
updateAccessToken方法,确保更新操作也包含新字段。在Token生成阶段完成赋值
通过自定义TokenEnhancer在AccessToken创建时赋值:public class CustomTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map<String, Object> additionalInfo = new HashMap<>(); // 根据业务场景设置自定义字段值,比如从用户信息中获取 additionalInfo.put("customField", "your_custom_value"); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; } }然后在授权服务器配置中注入该
TokenEnhancer,确保生成token时执行增强逻辑。排查缓存与编译问题
若项目用了Redis或本地缓存存储token,需清理缓存淘汰旧数据;同时确认项目已重新编译,避免使用未更新的class文件导致字段未被识别。验证数据库写入权限
检查操作数据库的账号是否拥有oauth_access_token表新增字段的写入权限,避免因权限不足导致赋值失败。
内容的提问来源于stack exchange,提问作者Gowthami Reddy
相关产品推荐
相关产品推荐

