package cn.reghao.tnb.auth.app.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;

/**
 * OAuth2 认证服务器配置
 *
 * @author reghao
 * @date 2023-02-07 15:18:20
 */
//@Configuration
//@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private DataSource dataSource;
    @Autowired
    public UserDetailsService userDetailsService;

    /*public OAuth2AuthorizationConfig(@Qualifier("oAuth2UserDetailsService") UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }*/

    @Bean
    public JdbcClientDetailsService jdbcClientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 客户端配置
     *
     * @param
     * @return
     * @date 2023-02-09 16:08:57
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(jdbcClientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 用户表单登入认证
                .authenticationManager(authenticationManager)
                // refresh_token 时需要加载用户信息
                .userDetailsService(userDetailsService)
                .accessTokenConverter(jwtAccessTokenConverter())
                // 存储访问令牌
                .tokenStore(tokenStore())
                // 存储授权记录
                .approvalStore(approvalStore())
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    /**
     * 安全配置
     *
     * @param
     * @return
     * @date 2023-02-09 16:06:38
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                // 用于校验 clientId + clientSecret
                //.passwordEncoder()
                ///.tokenKeyAccess("isAuthenticated()")
                // default is denyAll()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");

        security.authenticationEntryPoint(new MyAuthenticationEntryPoint());
        //security.realm("qq");
        // 允许客户端进行表单认证
        security.allowFormAuthenticationForClients();
    }

    /**
     * 令牌存储
     *
     * @param
     * @return
     * @date 2023-02-09 14:53:13
     */
    @Bean
    public TokenStore tokenStore() {
        //return new RedisTokenStore(redisConnectionFactory);
        //return new JdbcTokenStore(dataSource);
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 访问令牌转换器
     *
     * @param
     * @return
     * @date 2023-02-09 14:53:31
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("123456");
        return jwtAccessTokenConverter;
    }

    /**
     * 授权记录存储
     *
     * @param
     * @return
     * @date 2023-02-09 14:54:22
     */
    @Bean
    public ApprovalStore approvalStore() {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore());
        return store;
    }
}
