解决Micronaut多Bean候选者冲突及响应类型转换问题
问题解决:Micronaut 4.2.1自定义OpenIdAuthenticationMapper的两个问题
1. 多Bean候选注入报错解决
报错核心是系统中同时存在DefaultOpenIdAuthenticationMapper和你的MyOpenIdAuthenticationMapper两个OpenIdAuthenticationMapper实现类,容器无法确定注入哪一个。提供两种可行解决方式:
方案一:给自定义Mapper添加@Primary注解
让容器优先选择你的自定义实现,修改代码如下:
@Singleton @Primary // 添加该注解指定优先候选 class MyOpenIdAuthenticationMapper( ... ) : OpenIdAuthenticationMapper { // 原有实现逻辑不变 }
方案二:禁用默认的AuthenticationMapper
在配置文件(如application.yml)中添加配置,关闭默认实现:
micronaut: security: oauth2: openid: authentication-mapper: enabled: false
注意:你之前添加的
@Named("my")注解在此场景无效,因为DefaultOpenIdAuthorizationResponseHandler是按类型注入OpenIdAuthenticationMapper,而非按名称匹配。
2. 转换AuthenticationResponse.success为Publisher
你当前的Mono.create用法错误,正确的转换方式有两种,根据场景选择:
场景一:同步返回结果
直接用Mono.just()包装成功响应即可,这是最简单的方式:
override fun createAuthenticationResponse( providerName: String, tokenResponse: OpenIdTokenResponse, openIdClaims: OpenIdClaims, state: State? ): Publisher<AuthenticationResponse> { // 调用OAuth服务器逻辑... val attributes = mapOf( // 自定义属性内容 ) return Mono.just(AuthenticationResponse.success(identificationCode, emptyList(), attributes)) }
场景二:异步处理逻辑(如调用OAuth服务器是异步操作)
如果调用OAuth服务器的逻辑是异步的,可使用Mono.fromCallable()包装同步逻辑,自动转为异步流:
override fun createAuthenticationResponse( providerName: String, tokenResponse: OpenIdTokenResponse, openIdClaims: OpenIdClaims, state: State? ): Publisher<AuthenticationResponse> { return Mono.fromCallable { // 这里写同步的OAuth服务器调用逻辑 val identificationCode = fetchIdentificationCodeFromOAuthServer() AuthenticationResponse.success(identificationCode, emptyList(), emptyMap()) } }
内容的提问来源于stack exchange,提问作者BlackLotus
相关产品推荐
相关产品推荐

