Spring 安全+火力地堡

标签 spring spring-boot spring-security firebase-authentication spring-security-oauth2

我在 Spring Boot 和 oauth2(由 Google 提供)上编写了 rest 后端,在 "/login" 上自动重定向。除了 web 的 oauth 之外,我还想在移动后端进行 Firebase 身份验证,就像下面的算法一样:

User authorizes on mobile -> User sends request -> Backend gets request -> Backend checks if user openid exists in local 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>

您可以引用此 page 为您的 Firebase 项目下载 Configuration.json

关于 Spring 安全+火力地堡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62228686/

相关文章:

java - Spring:使用@Qualifier和@Profile

spring-boot - Spring Security中AuthenticationManager和AuthenticationProvider Authenticate方法的区别

spring-mvc - 如何在 Spring 启动时使用keycloak获取userinfo?

java - 为新的 Spring MVC 项目选择 Thymeleaf 和 A​​ngular

java - 如何在托管 Bean (JSF) 中 @Autowire BeanFactory

java - 需要最佳的实体和查询设计来获取具有多个关联的对象

java - 如何修复 org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean with name 'name' ?

java - Spring Boot OAuth2 单点注销(注销)

Java 8 元空间 : OutOfMemoryError: Dealing with reflection Inflation

java - 如何在spring-boot中禁用控制台日志记录?