Spring Authorization Server实现Oauth2

文章目录

  • maven 引入jar
  • 编写AuthorizationServerConfiguration
  • 编写SerurityConfiguration

maven 引入jar

<dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-oauth2-authorization-serverartifactId>
    <version>x.y.zversion>
dependency>

编写AuthorizationServerConfiguration

@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfiguration {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(Customizer.withDefaults()).build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) {
        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("demo")
                .clientName("demo")
                .clientSecret(passwordEncoder.encode("secret"))
                // AUTHORIZATION_CODE 模式对应 ClientAuthenticationMethod.CLIENT_SECRET_BASIC
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                // CLIENT_CREDENTIALS 模式对应 ClientAuthenticationMethod.CLIENT_SECRET_POST
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
                // PASSWORD 模式 Oauth2.1 已经弃用,官方没实现
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                .redirectUri("http://127.0.0.1:8080")
                .scope("user")
                .build();
        // 可以用jdbc,在org.springframework.security.oauth2.server.authorization.client下有创建表的SQL
        return new InMemoryRegisteredClientRepository(registeredClient);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(UUID.randomUUID().toString()).build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://localhost:8888").build();
    }

}

编写SerurityConfiguration

@EnableWebSecurity
public class SerurityConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests -> authorizeRequests.antMatchers("/actuator/**").anonymous().anyRequest().authenticated())
                .formLogin(withDefaults()).httpBasic()
                .and().cors().disable()
                .csrf().disable();
        return http.build();
    }

    @Bean
    public UserDetailsService users(PasswordEncoder passwordEncoder) {
        return new InMemoryUserDetailsManager(User.builder().username("admin").password(passwordEncoder.encode("password")).roles("USER").build());
    }
}

你可能感兴趣的:(Spring,Boot,spring,java,后端)