SecurityConfiguration.java 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. package com.jkcredit.invoice.hub.config;
  2. import org.springframework.beans.factory.BeanInitializationException;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Import;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  8. import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
  9. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  10. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  11. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  12. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  13. import org.springframework.security.config.http.SessionCreationPolicy;
  14. import org.springframework.security.core.userdetails.UserDetailsService;
  15. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  16. import org.springframework.security.crypto.password.PasswordEncoder;
  17. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  18. import org.springframework.web.filter.CorsFilter;
  19. import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
  20. import javax.annotation.PostConstruct;
  21. /**
  22. * @description:
  23. * @author: xusonglin
  24. * @create: 2020/1/3 10:14
  25. * @version: V1.0
  26. **/
  27. @EnableWebSecurity
  28. @EnableGlobalMethodSecurity(prePostEnabled = true)
  29. @Import(SecurityProblemSupport.class)
  30. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  31. @Autowired
  32. AjaxAuthenticationEntryPoint authenticationEntryPoint; // 未登陆时返回 JSON 格式的数据给前端(否则为 html)
  33. @Autowired
  34. AjaxAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功返回的 JSON 格式数据给前端(否则为 html)
  35. @Autowired
  36. AjaxAuthenticationFailureHandler authenticationFailureHandler; // 登录失败返回的 JSON 格式数据给前端(否则为 html)
  37. @Autowired
  38. AjaxLogoutSuccessHandler logoutSuccessHandler; // 注销成功返回的 JSON 格式数据给前端(否则为 登录时的 html)
  39. @Autowired
  40. AjaxAccessDeniedHandler accessDeniedHandler; // 无权访问返回的 JSON 格式数据给前端(否则为 403 html 页面)
  41. @Autowired
  42. JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; // JWT 拦截器
  43. private final UserDetailsService userDetailsService;
  44. private final AuthenticationManagerBuilder authenticationManagerBuilder;
  45. private final AuthenticationEntryPointHandler authenticationEntryPointHandler;
  46. private final CorsFilter corsFilter;
  47. public SecurityConfiguration(UserDetailsService userDetailsService, AuthenticationManagerBuilder authenticationManagerBuilder,
  48. AuthenticationEntryPointHandler authenticationEntryPointHandler,
  49. CorsFilter corsFilter) {
  50. this.userDetailsService = userDetailsService;
  51. this.authenticationManagerBuilder = authenticationManagerBuilder;
  52. this.authenticationEntryPointHandler = authenticationEntryPointHandler;
  53. this.corsFilter = corsFilter;
  54. }
  55. @PostConstruct
  56. public void init() {
  57. try {
  58. authenticationManagerBuilder
  59. .userDetailsService(userDetailsService)
  60. .passwordEncoder(passwordEncoder());
  61. } catch (Exception e) {
  62. throw new BeanInitializationException("Security configuration failed", e);
  63. }
  64. }
  65. @Bean
  66. @Override
  67. public AuthenticationManager authenticationManagerBean() throws Exception {
  68. return super.authenticationManagerBean();
  69. }
  70. // 此处需要使用@Bean引入,作用不是为了上面方法中使用
  71. // 作用在于使用@Bean将PasswordEncoder作为Bean引入
  72. // 同时此方法也可以指定加密方式
  73. @Bean
  74. public PasswordEncoder passwordEncoder() {
  75. return new BCryptPasswordEncoder();
  76. }
  77. @Override
  78. protected void configure(HttpSecurity http) throws Exception {
  79. // 去掉 CSRF
  80. http.csrf().disable()
  81. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT,关闭token
  82. .and()
  83. .httpBasic().authenticationEntryPoint(authenticationEntryPoint)
  84. .and()
  85. .authorizeRequests()
  86. .antMatchers("/api/**").permitAll()
  87. .anyRequest()
  88. .access("@rbacauthorityservice.hasPermission(request,authentication)") // RBAC 动态 url 认证
  89. .and()
  90. .formLogin() //开启登录
  91. .successHandler(authenticationSuccessHandler) // 登录成功
  92. .failureHandler(authenticationFailureHandler) // 登录失败
  93. .permitAll()
  94. .and()
  95. .logout()
  96. .logoutSuccessHandler(logoutSuccessHandler)
  97. .permitAll();
  98. // 记住我
  99. http.rememberMe().rememberMeParameter("remember-me")
  100. .userDetailsService(userDetailsService).tokenValiditySeconds(3600);
  101. http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据
  102. http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter
  103. }
  104. // @Override
  105. // protected void configure(HttpSecurity http) throws Exception {
  106. // http
  107. // .exceptionHandling()
  108. // .authenticationEntryPoint(authenticationEntryPointHandler)
  109. // .and()
  110. // .csrf().disable()//禁用了 csrf 功能
  111. // .authorizeRequests()//限定签名成功的请求
  112. // .antMatchers("/api/**").permitAll()//不拦截 oauth 开放的资源
  113. // .anyRequest().authenticated()// 其他请求进行拦截
  114. // .and()
  115. // .formLogin()
  116. // .loginProcessingUrl("/login")//使用 spring security 默认登录页面
  117. // .successHandler(customAuthenticationSuccess)
  118. // .failureHandler(customAuthenticationFailure)
  119. // .permitAll()
  120. // .and()
  121. // .logout()
  122. // .logoutUrl("/logout")
  123. // .permitAll();
  124. // }
  125. @Override
  126. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  127. auth
  128. .userDetailsService(userDetailsService)
  129. .passwordEncoder(passwordEncoder());
  130. }
  131. }