WebAppConfig.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package org.dbsyncer.web.config;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.dbsyncer.biz.ConfigService;
  4. import org.dbsyncer.biz.vo.RestResult;
  5. import org.dbsyncer.common.util.JsonUtil;
  6. import org.dbsyncer.common.util.SHA1Util;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.security.authentication.AuthenticationProvider;
  14. import org.springframework.security.authentication.BadCredentialsException;
  15. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  16. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  17. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  18. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  19. import org.springframework.security.core.Authentication;
  20. import org.springframework.security.core.AuthenticationException;
  21. import org.springframework.security.core.authority.AuthorityUtils;
  22. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  23. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
  24. import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import javax.servlet.http.HttpSessionEvent;
  28. import javax.servlet.http.HttpSessionListener;
  29. import java.io.IOException;
  30. import java.io.PrintWriter;
  31. /**
  32. * @author AE86
  33. * @version 1.0.0
  34. * @date 2019/10/23 23:57
  35. */
  36. @Configuration
  37. @EnableWebSecurity
  38. public class WebAppConfig extends WebSecurityConfigurerAdapter implements AuthenticationProvider, HttpSessionListener {
  39. private final Logger logger = LoggerFactory.getLogger(getClass());
  40. /**
  41. * 认证地址
  42. */
  43. private static final String LOGIN = "/login";
  44. /**
  45. * 认证页面
  46. */
  47. private static final String LOGIN_PAGE = "/login.html";
  48. /**
  49. * 404页面
  50. */
  51. private static final String ERROR_404_PAGE = "/404.html";
  52. /**
  53. * 每个帐号允许同时登录会话数, 默认同一个帐号只能在一个地方登录
  54. */
  55. private static final int MAXIMUM_SESSIONS = 1;
  56. @Value(value = "${dbsyncer.web.login.username}")
  57. private String username;
  58. @Autowired
  59. private ConfigService configService;
  60. /**
  61. * 登录失败
  62. *
  63. * @return
  64. */
  65. @Bean
  66. public AuthenticationFailureHandler loginFailHandler() {
  67. return new AuthenticationFailureHandler() {
  68. @Override
  69. public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
  70. write(response, RestResult.restFail(e.getMessage(), 401));
  71. }
  72. };
  73. }
  74. /**
  75. * 登录成功
  76. *
  77. * @return
  78. */
  79. @Bean
  80. public SavedRequestAwareAuthenticationSuccessHandler loginSuccessHandler() {
  81. return new SavedRequestAwareAuthenticationSuccessHandler() {
  82. @Override
  83. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
  84. Object principal = authentication.getPrincipal();
  85. logger.info("USER : " + principal + " LOGIN SUCCESS ! ");
  86. write(response, RestResult.restSuccess("登录成功!"));
  87. }
  88. };
  89. }
  90. @Bean
  91. public LogoutSuccessHandler logoutHandler() {
  92. return new LogoutSuccessHandler() {
  93. @Override
  94. public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
  95. try {
  96. Object principal = authentication.getPrincipal();
  97. logger.info("USER : {} LOGOUT SUCCESS ! ", principal);
  98. write(response, RestResult.restSuccess("注销成功!"));
  99. } catch (Exception e) {
  100. logger.info("LOGOUT EXCEPTION , e : {}", e.getMessage());
  101. write(response, RestResult.restFail(e.getMessage(), 403));
  102. }
  103. }
  104. };
  105. }
  106. @Override
  107. protected void configure(HttpSecurity http) throws Exception {
  108. //http.csrf().disable()
  109. // .authorizeRequests()
  110. // .anyRequest().permitAll()
  111. // .and().logout().permitAll();
  112. http.csrf().disable()
  113. .authorizeRequests()
  114. .antMatchers("/css/**", "/js/**", "/img/**", "/config/**", "/plugins/**").permitAll().anyRequest()
  115. .authenticated()
  116. .and()
  117. .formLogin()
  118. .loginProcessingUrl(LOGIN)
  119. .loginPage(LOGIN_PAGE)
  120. .successHandler(loginSuccessHandler())
  121. .failureHandler(loginFailHandler())
  122. .permitAll()
  123. .and()
  124. .logout()
  125. .permitAll()
  126. .invalidateHttpSession(true).deleteCookies("JSESSIONID").logoutSuccessHandler(logoutHandler())
  127. .and()
  128. .sessionManagement()
  129. .sessionFixation()
  130. .migrateSession()
  131. .maximumSessions(MAXIMUM_SESSIONS);
  132. }
  133. @Override
  134. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  135. // 获取表单用户名
  136. String username = (String) authentication.getPrincipal();
  137. // 获取表单用户填写的密码
  138. String password = (String) authentication.getCredentials();
  139. password = SHA1Util.b64_sha1(password);
  140. if (!StringUtils.equals(username, this.username) || !StringUtils.equals(configService.getPassword(), password)) {
  141. throw new BadCredentialsException("对不起,您输入的帐号或密码错误");
  142. }
  143. return new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  144. }
  145. @Override
  146. public boolean supports(Class<?> aClass) {
  147. return true;
  148. }
  149. @Override
  150. public void sessionCreated(HttpSessionEvent se) {
  151. logger.debug("创建会话:{}", se.getSession().getId());
  152. int maxInactiveInterval = se.getSession().getMaxInactiveInterval();
  153. logger.debug(String.valueOf(maxInactiveInterval));
  154. }
  155. @Override
  156. public void sessionDestroyed(HttpSessionEvent se) {
  157. logger.debug("销毁会话:{}", se.getSession().getId());
  158. }
  159. /**
  160. * 响应
  161. *
  162. * @param response
  163. * @param result
  164. */
  165. private void write(HttpServletResponse response, RestResult result) {
  166. PrintWriter out = null;
  167. try {
  168. response.setContentType("application/json;charset=utf-8");
  169. response.setStatus(result.getStatus());
  170. out = response.getWriter();
  171. out.write(JsonUtil.objToJson(result));
  172. out.flush();
  173. } catch (IOException e) {
  174. logger.error(e.getMessage());
  175. } finally {
  176. if (null != out) {
  177. out.close();
  178. }
  179. }
  180. }
  181. }