WebAppConfig.java 6.8 KB

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