我有休息的后端写在Spring Boot上,而oauth2(由Google提供)在"/login"
上自动重定向。我想在移动设备的后端进行Firebase身份验证,例如以下算法:
User authorizes on mobile -> User sends request -> Backend gets request -> Backend checks if user openid exists in database -> Backend returns response or exception page
以下代码是我当前的WebSecurityConfiguration:
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().mvcMatchers("/","/static/**","/public/**","/assets/**","/api/sensors/**", "/emulator/**").permitAll()
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and()
.csrf().disable();
}
@Bean
public PrincipalExtractor principalExtractor(PersonRepository personRepository) {
return map -> {
String id = (String) map.get("sub");
Person person1 = personRepository.findById(id).orElseGet(() -> {
Person person = new Person();
person.setPersonId(id);
person.getDetails().setFirstName((String) map.get("given_name"));
person.getDetails().setLastName((String) map.get("family_name"));
person.getDetails().setEmail((String) map.get("email"));
person.getDetails().setPictureUrl((String) map.get("picture"));
person.getSettings().setLocale(new Locale((String) map.get("locale")));
person.setPersonRole(PersonRole.USER);
person.setStatus(PersonStatus.NORMAL);
person.newToken();
return person;
});
return personRepository.save(person1);
};
}
}
添加以下形式的Firebase配置Bean:
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.firebase.*;
@Configuration
public class FirebaseConfig {
@Bean
public DatabaseReference firebaseDatabse() {
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
return firebase;
}
@Value("${firebase.database.url}")
private String databaseUrl;
@Value("${firebase.config.path}")
private String configPath;
@PostConstruct
public void init() {
/**
* https://firebase.google.com/docs/server/setup
*
* Create service account , download json
*/
InputStream inputStream = FirebaseConfig.class.getClassLoader().getResourceAsStream(configPath);
FirebaseOptions options = new FirebaseOptions.Builder().setServiceAccount(inputStream)
.setDatabaseUrl(databaseUrl).build();
FirebaseApp.initializeApp(options);
}
}
在application.properties
中,添加
firebase.config.path=Configuration.json
firebase.database.url=<firebase-database-path>
您可以通过参考此Configuration.json
为Firebase项目下载page