在Spring Boot中使用Firebase ID令牌验证用户,可以通过以下步骤实现:
pom.xml
文件中添加以下依赖:<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>7.0.0</version>
</dependency>
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
@Configuration
public class FirebaseConfig {
@PostConstruct
public void init() throws IOException {
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
}
}
请确保将path/to/serviceAccountKey.json
替换为你的服务账号密钥文件的实际路径。
verifyIdToken()
方法来验证令牌的有效性,并获取用户的相关信息。示例代码如下:import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class FirebaseTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public FirebaseTokenAuthenticationFilter(AuthenticationManager authenticationManager) {
super(new AntPathRequestMatcher("/api/**"));
setAuthenticationManager(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String idToken = request.getHeader("Authorization");
try {
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
String uid = decodedToken.getUid();
// 可以根据需要获取其他用户信息
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(uid, null)
);
} catch (FirebaseAuthException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
}
在上述代码中,我们通过Authorization
请求头获取ID令牌,并使用verifyIdToken()
方法验证令牌的有效性。如果验证成功,我们将用户的UID作为身份验证凭证,并将其传递给Spring Security进行后续处理。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private FirebaseTokenAuthenticationFilter firebaseTokenAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.addFilterBefore(firebaseTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
在上述代码中,我们将firebaseTokenAuthenticationFilter
添加到了UsernamePasswordAuthenticationFilter
之前,以确保在身份验证之前先进行Firebase ID令牌的验证。
至此,你已经完成了在Spring Boot中使用Firebase ID令牌验证用户的配置。在需要进行身份验证的接口上,你可以使用@PreAuthorize
注解来限制访问权限,例如:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/protected")
@PreAuthorize("isAuthenticated()")
public String protectedEndpoint() {
return "This is a protected endpoint.";
}
}
以上代码中,protectedEndpoint()
方法只允许已经通过Firebase ID令牌验证的用户访问。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)、腾讯云数据库MySQL版、腾讯云对象存储(COS)等。你可以在腾讯云官网上找到这些产品的详细介绍和文档。
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云