• SpringBoot集成security


    1.创建项目集成依赖

    1. org.springframework.boot
    2. spring-boot-starter-security
    1. @RestController
    2. public class Test {
    3. @GetMapping("/test")
    4. public String test(){
    5. return "test";
    6. }
    7. }

    下面用到的测试方法

    1. @RestController
    2. public class Test {
    3. @GetMapping("/test")
    4. public String test(){
    5. return "test";
    6. }
    7. @GetMapping("/admin/hello")
    8. public String testadmin(){
    9. return "admin";
    10. }
    11. @GetMapping("/user/hello")
    12. public String testuser(){
    13. return "user";
    14. }
    15. }

    用户名user   密码为项目日志打印

    2.配置访问用户名和密码

    1. spring.security.user.name=liuboss
    2. spring.security.user.password=123456
    3. spring.security.user.roles=admin

    3.添加配置类---配置用户名和密码。

    1. @Configuration
    2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    3. /*提供实例--不需要加密*/
    4. @Bean
    5. PasswordEncoder passwordEncoder(){
    6. return NoOpPasswordEncoder.getInstance();
    7. }
    8. @Override
    9. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    10. auth.inMemoryAuthentication()
    11. .withUser("boss").password("123").roles("admin")
    12. .and()
    13. .withUser("liuboss").password("123").roles("admin");
    14. }
    15. }

    4.配置访问角色和登录页面

    1. @Configuration
    2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    3. /*提供实例--不需要加密*/
    4. @Bean
    5. PasswordEncoder passwordEncoder(){
    6. return NoOpPasswordEncoder.getInstance();
    7. }
    8. @Override
    9. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    10. auth.inMemoryAuthentication()
    11. .withUser("admin").password("123").roles("admin")
    12. .and()
    13. .withUser("user").password("123").roles("user");
    14. }
    15. @Override
    16. protected void configure(HttpSecurity http) throws Exception {
    17. http.authorizeRequests()
    18. .antMatchers("/admin/**").hasRole("admin")
    19. .antMatchers("user/**").hasAnyRole("admin","user")
    20. .anyRequest().authenticated()
    21. .and()
    22. .formLogin()
    23. .loginProcessingUrl("/doLogin")
    24. .permitAll()
    25. .and()
    26. /*关闭攻击使用postman测试*/
    27. .csrf().disable();
    28. }
    29. }

    5.登陆表单的配置,增加登陆成功,登陆失败处理。

    1. @Configuration
    2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    3. /*提供实例--不需要加密*/
    4. @Bean
    5. PasswordEncoder passwordEncoder(){
    6. return NoOpPasswordEncoder.getInstance();
    7. }
    8. @Override
    9. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    10. auth.inMemoryAuthentication()
    11. .withUser("admin").password("123").roles("admin")
    12. .and()
    13. .withUser("user").password("123").roles("user");
    14. }
    15. @Override
    16. protected void configure(HttpSecurity http) throws Exception {
    17. http.authorizeRequests()
    18. .antMatchers("/admin/**").hasRole("admin")
    19. .antMatchers("user/**").hasAnyRole("admin","user")
    20. .anyRequest().authenticated()
    21. .and()
    22. .formLogin()
    23. .loginProcessingUrl("/doLogin")
    24. /*跳转到登录页面*/
    25. .loginPage("/login")
    26. /*登陆成功的处理*/
    27. .successHandler(new AuthenticationSuccessHandler() {
    28. @Override
    29. public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
    30. resp.setContentType("application/json;charset=utf-8");
    31. PrintWriter out = resp.getWriter();
    32. HashMap map = new HashMap<>();
    33. map.put("status",200);
    34. map.put("msg",authentication.getPrincipal());
    35. out.write(new ObjectMapper().writeValueAsString(map));
    36. out.flush();
    37. out.close();
    38. }
    39. })
    40. /*登陆失败的处理*/
    41. .failureHandler(new AuthenticationFailureHandler() {
    42. @Override
    43. public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
    44. resp.setContentType("application/json;charset=utf-8");
    45. PrintWriter out = resp.getWriter();
    46. HashMap map = new HashMap<>();
    47. map.put("status",401);
    48. if (e instanceof LockedException){
    49. map.put("msg","账户被锁定,登录失败");
    50. } else if (e instanceof BadCredentialsException){
    51. map.put("msg","账户名或密码错误,登录失败");
    52. } else if (e instanceof DisabledException){
    53. map.put("msg","账户被禁用,登录失败");
    54. } else if (e instanceof AccountExpiredException){
    55. map.put("msg","账户过期登录失败");
    56. } else {
    57. map.put("msg","登录失败");
    58. }
    59. out.write(new ObjectMapper().writeValueAsString(map));
    60. out.flush();
    61. out.close();
    62. }
    63. })
    64. .permitAll()
    65. .and()
    66. /*关闭攻击使用postman测试*/
    67. .csrf().disable();
    68. }
    69. }

    6.多个http   security  的配置。

    1. @Configuration
    2. public class MultHttpSecurityConfig {
    3. /*提供实例--不需要加密*/
    4. @Bean
    5. PasswordEncoder passwordEncoder(){
    6. return NoOpPasswordEncoder.getInstance();
    7. }
    8. @Autowired
    9. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    10. auth.inMemoryAuthentication()
    11. .withUser("admin").password("1234").roles("admin")
    12. .and()
    13. .withUser("user").password("1234").roles("user");
    14. }
    15. /*多个http配置*/
    16. @Configuration
    17. /*@Order(1) 为访问优先级,数字越低,优先级越高*/
    18. @Order(1)
    19. public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
    20. @Override
    21. protected void configure(HttpSecurity http) throws Exception {
    22. http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
    23. }
    24. }
    25. @Configuration
    26. public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
    27. @Override
    28. protected void configure(HttpSecurity http) throws Exception {
    29. http.authorizeRequests().anyRequest().authenticated()
    30. .and()
    31. .formLogin()
    32. .loginProcessingUrl("/doLogin")
    33. .permitAll()
    34. .and()
    35. .csrf().disable();
    36. }
    37. }
    38. }

     

    7.密码加密  使用此方式

    1. @org.junit.jupiter.api.Test
    2. public void contentLoads(){
    3. for (int i = 0; i < 10; i++) {
    4. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    5. System.out.println(encoder.encode("123456"));
    6. }
    7. }

    8.配置密码加密方式

    1. @Configuration
    2. public class MultHttpSecurityConfig {
    3. /*提供实例--不需要加密*/
    4. @Bean
    5. PasswordEncoder passwordEncoder(){
    6. /*return NoOpPasswordEncoder.getInstance();*/
    7. /*使用BCryptPasswordEncoder加密方式*/
    8. return new BCryptPasswordEncoder();
    9. }
    10. @Autowired
    11. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    12. auth.inMemoryAuthentication()
    13. .withUser("admin").password("$2a$10$/NB.L1nOJnBPsi3KTfvJfuoZCbOf.choREFrVZQXqCldfa0a3KNtq").roles("admin")
    14. .and()
    15. .withUser("user").password("$2a$10$4zwF70VbjE67IgiVmpLGVeuvg59DyJh/BN60drYw96XkHshXnln7K").roles("user");
    16. }
    17. /*多个http配置*/
    18. @Configuration
    19. /*@Order(1) 为访问优先级,数字越低,优先级越高*/
    20. @Order(1)
    21. public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
    22. @Override
    23. protected void configure(HttpSecurity http) throws Exception {
    24. http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
    25. }
    26. }
    27. @Configuration
    28. public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
    29. @Override
    30. protected void configure(HttpSecurity http) throws Exception {
    31. http.authorizeRequests().anyRequest().authenticated()
    32. .and()
    33. .formLogin()
    34. .loginProcessingUrl("/doLogin")
    35. .permitAll()
    36. .and()
    37. .csrf().disable();
    38. }
    39. }
    40. }

    9.方法的安全

    配置类

    1. @Configuration
    2. /*开启方法安全*/
    3. @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
    4. public class MultHttpSecurityConfig {
    5. /*提供实例--不需要加密*/
    6. @Bean
    7. PasswordEncoder passwordEncoder(){
    8. /*return NoOpPasswordEncoder.getInstance();*/
    9. /*使用BCryptPasswordEncoder加密方式*/
    10. return new BCryptPasswordEncoder();
    11. }
    12. @Autowired
    13. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    14. auth.inMemoryAuthentication()
    15. .withUser("admin").password("$2a$10$/NB.L1nOJnBPsi3KTfvJfuoZCbOf.choREFrVZQXqCldfa0a3KNtq").roles("admin")
    16. .and()
    17. .withUser("user").password("$2a$10$4zwF70VbjE67IgiVmpLGVeuvg59DyJh/BN60drYw96XkHshXnln7K").roles("user");
    18. }
    19. /*多个http配置*/
    20. @Configuration
    21. /*@Order(1) 为访问优先级,数字越低,优先级越高*/
    22. @Order(1)
    23. public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
    24. @Override
    25. protected void configure(HttpSecurity http) throws Exception {
    26. http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
    27. }
    28. }
    29. @Configuration
    30. public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
    31. @Override
    32. protected void configure(HttpSecurity http) throws Exception {
    33. http.authorizeRequests().anyRequest().authenticated()
    34. .and()
    35. .formLogin()
    36. .loginProcessingUrl("/doLogin")
    37. .permitAll()
    38. .and()
    39. .csrf().disable();
    40. }
    41. }
    42. }

    service层配置

    1. @Service
    2. public class MethodService {
    3. @PreAuthorize("hasAnyRole('admin')")
    4. public String admin(){
    5. return "hello admin";
    6. }
    7. @Secured("ROLB_user")
    8. public String user(){
    9. return "hello user";
    10. }
    11. @PreAuthorize("hasAnyRole('admin','user')")
    12. public String hello (){
    13. return "hello hello";
    14. }
    15. }

    controller运用

    1. @Autowired
    2. MethodService methodService;
    3. @GetMapping("/hello1")
    4. public String hello1(){
    5. return methodService.admin();
    6. }
    7. @GetMapping("/hello2")
    8. public String hello2(){
    9. return methodService.user();
    10. }
    11. @GetMapping("/hello3")
    12. public String hello3(){
    13. return methodService.hello();
    14. }

  • 相关阅读:
    笙默考试管理系统-MyExamTest----codemirror(30)
    matlab图像类型的转换九种
    【Android性能优化】:ProGuard,混淆,R8优化
    华为回击:制裁无法阻挡中国科技创新 | 百能云芯
    vuex存储用户信息封装
    这3个图表“小心机”,用对了雪中送炭,用错了是惨不忍睹
    vue大型电商项目尚品汇(后台终结篇)day06 重磅!!!
    人大金仓分析型数据库COPY装载数据
    IDEA启动C:\Users\badboy\.jdks\corretto-17.0.7\bin\java.exe -Xmx700m报错
    什么是单子?Java 开发人员的基本理论
  • 原文地址:https://blog.csdn.net/qq_39696115/article/details/128052008