admin
2021-06-24 df4441322e9801c102299451da41d7c40b4502e9
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package com.ks.daylucky.config;
 
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.ks.daylucky.util.Constant;
import com.ks.lucky.pojo.DO.LuckySponsors;
import com.ks.lucky.remote.service.LuckySponsorService;
import net.sf.json.JSONObject;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.filter.OncePerRequestFilter;
import org.yeshi.utils.StringUtil;
 
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
 
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Reference(version = "1.0.0")
    private LuckySponsorService luckySponsorService;
 
    private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
 
 
    private final String LOGIN_PROCESSING_URL = "/admin/api/user/login";
 
    //图形验证码配置
    @Bean
    public Producer captcha() {
        Properties properties = new Properties();
        //图片的宽高
        properties.setProperty("kaptcha.image.width", "150");
        properties.setProperty("kaptcha.image.height", "50");
        //字符集
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
        //字符长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
 
        String color = "0,0,0";
 
        //边框颜色
        properties.setProperty("kaptcha.border.color", color);
        //字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", color);
        //干扰颜色
        properties.setProperty("kaptcha.noise.color", color);
 
 
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
 
    public class VerificationCodeException extends AuthenticationException {
        public VerificationCodeException() {
            super("图形验证码校验失败");
        }
    }
 
 
    //验证码过滤器
    class VerificationCodeFilter extends OncePerRequestFilter {
        private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", 11);
                jsonObject.put("msg", "验证码错误");
                httpServletResponse.getWriter().print(jsonObject);
            }
        };
 
        @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
            if (!LOGIN_PROCESSING_URL.equalsIgnoreCase(httpServletRequest.getRequestURI())) {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } else {
                try {
                    verificationCode(httpServletRequest);
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                } catch (VerificationCodeException e) {
                    authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                }
            }
        }
 
        private void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {
            String requestCode = httpServletRequest.getParameter("captcha");
            HttpSession httpSession = httpServletRequest.getSession();
            String captcha = httpSession.getAttribute("captcha") + "";
            httpSession.removeAttribute("captcha");
            if (StringUtil.isNullOrEmpty(captcha) || StringUtil.isNullOrEmpty(requestCode) || !captcha.equalsIgnoreCase(requestCode)) {
                throw new VerificationCodeException();
            }
 
 
        }
    }
 
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/admin/api/captcha.jpg*").permitAll()
                .antMatchers("/admin/api/**", "/index.html").authenticated()
                .and()
                .formLogin()
                //自定义登录界面
                .loginPage("/admin/login.html")
                //设置接收的属性字段
                .usernameParameter("account")
                .passwordParameter("pwd")
                //处理登录逻辑的url
                .loginProcessingUrl(LOGIN_PROCESSING_URL)
                //登录成功后的跳转
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        SecurityUser user = (SecurityUser) authentication.getPrincipal();
                        LuckySponsors sponsors =user.getSponsors();
                        httpServletRequest.getSession().setAttribute(Constant.SESSION_ADMIN_SPONSOR_KEY, sponsors);
                        logger.info("successHandler");
                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", 0);
                        jsonObject.put("msg", "登录成功");
                        httpServletResponse.getWriter().print(jsonObject);
                    }
                })
                //登录失败后的处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        logger.info("failureHandler");
                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", 1);
                        if (e instanceof UsernameNotFoundException) {
                            jsonObject.put("msg", "用户不存在");
                        } else {
                            jsonObject.put("msg", e.getMessage());
                        }
                        httpServletResponse.getWriter().print(jsonObject);
                    }
                })
                .permitAll()
                .and()
                //退出登录
                .logout().logoutUrl("/admin/api/logout").logoutSuccessHandler(new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                logger.info("onLogoutSuccess");
            }
        })
                .and()
                .csrf().disable()
                .rememberMe().userDetailsService(new MyUserDetailsService());
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new MyAuthenticationProvider(new MyUserDetailsService(), new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }
 
            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equalsIgnoreCase(charSequence.toString());
            }
        }));
 
    }
 
    class SecurityUser implements UserDetails {
 
        private LuckySponsors sponsors;
 
        public SecurityUser() {
 
        }
 
        public SecurityUser(LuckySponsors sponsors) {
            this.sponsors = sponsors;
        }
 
        public LuckySponsors getSponsors() {
            return sponsors;
        }
 
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("admin");
            authorities.add(authority);
            return authorities;
        }
 
        @Override
        public String getPassword() {
            return sponsors.getPwd();
        }
 
        @Override
        public String getUsername() {
            return sponsors.getName();
        }
 
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
 
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
 
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
 
        @Override
        public boolean isEnabled() {
            return true;
        }
    }
 
    class MyUserDetailsService implements UserDetailsService {
 
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            LuckySponsors sponsors = luckySponsorService.getSponsorByAccount(s);
            if (sponsors == null) {
                throw new UsernameNotFoundException("账户不存在");
            }
            //TODO 用户权限赋予
            return new SecurityUser(sponsors);
        }
    }
 
    class MyAuthenticationProvider extends DaoAuthenticationProvider {
 
        public MyAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
            this.setUserDetailsService(userDetailsService);
            this.setPasswordEncoder(passwordEncoder);
        }
 
        @Override
        protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
            if (usernamePasswordAuthenticationToken.getCredentials() == null) {
                throw new BadCredentialsException("密码不能为空");
            }
            String pwd = usernamePasswordAuthenticationToken.getCredentials().toString();
            if (!pwd.equalsIgnoreCase(userDetails.getPassword())) {
                throw new BadCredentialsException("密码错误");
            }
        }
 
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            // 获取前端表单中输入后返回的用户名、密码
            String userName = (String) authentication.getPrincipal();
            String password = StringUtil.Md5((String) authentication.getCredentials());
 
            SecurityUser userInfo = (SecurityUser) this.getUserDetailsService().loadUserByUsername(userName);
 
            boolean isValid = password.equalsIgnoreCase(userInfo.getPassword());
            // 验证密码
            if (!isValid) {
                throw new BadCredentialsException("密码错误!");
            }
            return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
        }
    }
}