在Java中请求ID令牌

时间:2018-05-27 21:03:18

标签: java firebase firebase-authentication

我正在开发一个Spring Boot REST API,它使用Firebase进行身份验证(即,它使用Admin SDK来验证传递的ID令牌)。我使用标准的Firebase ID令牌而无需自定义身份验证。

Spring AuthenticationProvider

@Component
class FirebaseAuthenticationProvider(private val firebaseAuth: FirebaseAuth) :
        AbstractUserDetailsAuthenticationProvider() {

    override fun supports(authentication: Class<*>?): Boolean {
        return FirebaseAuthenticationToken::class.java.isAssignableFrom(authentication)
    }

    override fun retrieveUser(username: String?, authentication: UsernamePasswordAuthenticationToken?): UserDetails {
        var firebaseAuthenticationToken = authentication as FirebaseAuthenticationToken

        val task = firebaseAuth.verifyIdTokenAsync(firebaseAuthenticationToken.token)

        try {
            val firebaseToken = task.get()
            return FirebaseUserDetails(firebaseToken.email, firebaseToken.uid)
        } catch (e: Exception) {
            when (e) {
                is InterruptedException, is ExecutionException -> {
                    throw SessionAuthenticationException(e.message)
                }
                else -> throw e
            }
        }

    }

    override fun additionalAuthenticationChecks(userDetails: UserDetails?,
                                                authentication: UsernamePasswordAuthenticationToken?) {
        // nothing to do here
    }

}

我想集成测试提取令牌的组件并通过Admin SDK进行验证。为此,我想模拟一个Android客户端,并在每次测试运行时为测试用户检索一个新的ID令牌。

例如

@Test
fun `accepts valid token`() {

    // HOW TO DO THIS       
    val testToken: String = ???????????

    println("Acquired token $testToken")

    mockMvc.perform(get("/").header(FirebaseAuthenticationTokenFilter.TOKEN_HEADER, testToken))
            .andExpect(status().isOk)   
}

如果给出正确的电子邮件和密码,如何在纯Java中检索有效的ID令牌?

我尝试使用IdentityToolkit REST API

private fun getTokenForTestUser() : String {
    val restClient = RestTemplate()
    val json = JSONObject().put("email", testUsername).put("password", testPassword)
    val headers = HttpHeaders()
    headers.contentType = MediaType.APPLICATION_JSON
    headers.accept = listOf(MediaType.APPLICATION_JSON)
    val request = HttpEntity(json.toString(), headers)

    val response = restClient.postForObject(
            "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=$testApiKey",
            request, Map::class.java) as Map<String, String>

    return response["idToken"]!!
}

但这不起作用,因为检索到的令牌缺少必需的颁发者字段。

0 个答案:

没有答案