forked from kidgrow-microservices-platform

luliqiang
2020-12-31 6fb14149d62199cfcc0448c82eb2f51f9c5181de
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package com.kidgrow.oauth2.config;
 
import com.kidgrow.oauth2.handler.SingleTokenServices;
import com.kidgrow.oauth2.service.impl.RedisClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
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.configuration.EnableAuthorizationServer;
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.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
 
import javax.annotation.Resource;
import java.util.Arrays;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: OAuth2 授权服务器配置<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/20 09:19 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * 注入authenticationManager 来支持 password grant type
     */
//   @Autowired
//    private AuthenticationManager authenticationManager;
 
 
    @Resource
    private UserDetailsService userDetailsService;
 
 
    @Autowired
    private TokenStore tokenStore;
 
//    @Autowired
//    private CustomRedisTokenStore tokenStore;
 
    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;
 
    @Autowired(required = false)
    private TokenEnhancer tokenEnhancer;
 
    @Autowired
    private WebResponseExceptionTranslator webResponseExceptionTranslator;
 
    @Autowired
    private RedisClientDetailsService clientDetailsService;
 
    @Autowired
    private RandomValueAuthorizationCodeServices authorizationCodeServices;
    @Autowired
    private AuthenticationProvider daoAuhthenticationOauthProvider;
//    @Autowired
//    private SingleTokenServices tokenServices;
 
 
    /**
     * 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        if (jwtAccessTokenConverter != null) {
            if (tokenEnhancer != null) {
                TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
                tokenEnhancerChain.setTokenEnhancers(
                        Arrays.asList(tokenEnhancer, jwtAccessTokenConverter));
                endpoints.tokenEnhancer(tokenEnhancerChain);
            } else {
                endpoints.accessTokenConverter(jwtAccessTokenConverter);
            }
        }
        endpoints
                //扩展tokenServices
                .tokenServices(KidgrowTokenServices())
                .authenticationManager(new AuthenticationManager(){
                    @Override
                    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                        String token = (String) authentication.getPrincipal();
                        OAuth2Authentication auth = KidgrowTokenServices().loadAuthentication(token);
                        if (auth == null) {
                            throw new InvalidTokenException("Invalid token: " + token);
                        }
                        return daoAuhthenticationOauthProvider.authenticate(authentication);
                    }
                })
                .userDetailsService(userDetailsService)
                .authorizationCodeServices(authorizationCodeServices)
                .exceptionTranslator(webResponseExceptionTranslator);
 
    }
    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider(){
 
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
 
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
 
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
 
        return daoAuthenticationProvider;
 
    }
 
    @Bean
    @Primary
    @Lazy
    public SingleTokenServices KidgrowTokenServices(){
        SingleTokenServices tokenServices = new SingleTokenServices();
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setSupportRefreshToken(true);//支持刷新token
        tokenServices.setReuseRefreshToken(true);
        addUserDetailsService(tokenServices, this.userDetailsService);
        return tokenServices;
    }
 
//    private SingleTokenServices tokenServices(AuthorizationServerEndpointsConfigurer endpoints) {
//        SingleTokenServices tokenServices = new SingleTokenServices();
//        tokenServices.setTokenStore(tokenStore);
//        tokenServices.setSupportRefreshToken(true);//支持刷新token
//        tokenServices.setReuseRefreshToken(true);
//        tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
//        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
//        addUserDetailsService(tokenServices, this.userDetailsService);
//        return tokenServices;
//    }
//    private void addUserDetailsService(SingleTokenServices tokenServices, UserDetailsService userDetailsService) {
//        if (userDetailsService != null) {
//            PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
//            provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(
//                    userDetailsService));
//            tokenServices.setAuthenticationManager(new ProviderManager(Arrays.asList(provider)));
//        }
//    }
 
    private void addUserDetailsService(SingleTokenServices tokenServices, UserDetailsService userDetailsService) {
        if (userDetailsService != null) {
            PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
            provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(
                    userDetailsService));
            tokenServices.setAuthenticationManager(new ProviderManager(Arrays.asList(provider)));
        }
    }
 
    /**
     * 配置应用名称 应用id
     * 配置OAuth2的客户端相关信息
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
        clientDetailsService.loadAllClientToCache();
    }
 
    /**
     * 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
     * @param security
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()")
                //让/oauth/token支持client_id以及client_secret作登录认证
                .allowFormAuthenticationForClients();
    }
}