Warning: mkdir(): No space left on device in /data/discuz/upload/source/class/class_core.php on line 91
SpringBoot整合Spring Security使用Demo-SpringBoot,整合,Spring,Security,使用-IT技术擎-最棒的IT web技术交流社区-( it.techqing.com)
设为首页收藏本站

IT技术擎 - 最棒的IT web技术交流社区

 找回密码
 注册为IT技术擎人

QQ登录

只需一步,快速开始

搜索
热搜: php h5 jquery
查看: 49|回复: 0

[框架开发] SpringBoot整合Spring Security使用Demo

[复制链接]

1万

主题

1万

帖子

5万

积分

版主

Rank: 7Rank: 7Rank: 7

积分
54102
发表于 2019-8-23 07:10:17 | 显示全部楼层 |阅读模式
https://start.spring.io/ 生成SpringBoot项目
pom文件应该是我这样的:
  1. <?xml version="1.0" encoding="UTF-8"? >
  2. <
  3. project xmlns="http://maven.apache.org/POM/4.0.0"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
  6. <
  7. modelVersion >4.0.0 </modelVersion >
  8. <
  9. parent >
  10. <
  11. groupId >org.springframework.boot </groupId >
  12. <
  13. artifactId >spring-boot-starter-parent </artifactId >
  14. <
  15. version >1.5.20.RELEASE </version >
  16. <
  17. relativePath / >
  18. <!--lookup parent from repository -- >
  19. </parent >
  20. <
  21. groupId >org.dreamtech </groupId >
  22. <
  23. artifactId >demo </artifactId >
  24. <
  25. version >0.0.1-SNAPSHOT </version >
  26. <
  27. packaging >war </packaging >
  28. <
  29. name >demo </name >
  30. <
  31. description >Demo project for Spring Security </description >
  32. <
  33. properties >
  34. <
  35. java.version >1.8 </java.version >
  36. </properties >
  37. <
  38. dependencies >
  39. <
  40. dependency >
  41. <
  42. groupId >org.springframework.boot </groupId >
  43. <
  44. artifactId >spring-boot-starter-security </artifactId >
  45. </dependency >
  46. <
  47. dependency >
  48. <
  49. groupId >org.springframework.boot </groupId >
  50. <
  51. artifactId >spring-boot-starter-web </artifactId >
  52. </dependency >
  53. <!--在IDEA中如果项目运行失败,注释掉这一项即可 -- >
  54. <
  55. dependency >
  56. <
  57. groupId >org.springframework.boot </groupId >
  58. <
  59. artifactId >spring-boot-starter-tomcat </artifactId >
  60. <
  61. scope >provided </scope >
  62. </dependency >
  63. <
  64. dependency >
  65. <
  66. groupId >org.springframework.boot </groupId >
  67. <
  68. artifactId >spring-boot-starter-test </artifactId >
  69. <
  70. scope >test </scope >
  71. </dependency >
  72. <
  73. dependency >
  74. <
  75. groupId >org.springframework.security </groupId >
  76. <
  77. artifactId >spring-security-test </artifactId >
  78. <
  79. scope >test </scope >
  80. </dependency >
  81. </dependencies >
  82. <
  83. build >
  84. <
  85. plugins >
  86. <
  87. plugin >
  88. <
  89. groupId >org.springframework.boot </groupId >
  90. <
  91. artifactId >spring-boot-maven-plugin </artifactId >
  92. </plugin >
  93. </plugins >
  94. </build >
  95. </project >
复制代码
Controller:
  1. packageorg.dreamtech.demo;
  2. importorg.springframework.boot.SpringApplication;
  3. importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. importorg.springframework.boot.autoconfigure.SpringBootApplication;
  5. importorg.springframework.security.access.prepost.PreAuthorize;
  6. importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  7. importorg.springframework.web.bind.annotation.RequestMapping;
  8. importorg.springframework.web.bind.annotation.RestController;
  9. /**
  10. * Spring Boot启动类 * @authorXu Yiqing **/
  11. @SpringBootApplication@RestController@EnableAutoConfiguration@EnableGlobalMethodSecurity(prePostEnabled = true)
  12. publicclassDemoApplication {
  13. publicstaticvoidmain(String[] args) {
  14. SpringApplication.run(DemoApplication.class, args);
  15. }
  16. /**
  17. * 根目录,所有人都可以访问 * @return */
  18. @RequestMapping("/")publicString helloSpringBoot() {
  19. return"hello spring boot";
  20. }
  21. /**
  22. * 只有经过身份认证后才可以访问 * @return */
  23. @RequestMapping("/hello")publicString helloWorld() {
  24. return"hello world";
  25. }
  26. /**
  27. * 经过身份认证且身份必须是ADMIN才可以访问,并且是在方法执行前进行验证 * @return */
  28. @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping("/role")publicString role() {
  29. return"admin auth";
  30. }
  31. }
复制代码
Spring Security配置文件:
  1. packageorg.dreamtech.demo;
  2. importorg.springframework.beans.factory.annotation.Autowired;
  3. importorg.springframework.context.annotation.Configuration;
  4. importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  5. importorg.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. importorg.springframework.security.config.annotation.web.builders.WebSecurity;
  7. importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  8. importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. /**
  10. * Spring Security配置文件 * @authorXu Yiqing **/
  11. @Configuration@EnableWebSecurity
  12. publicclassSpringSecurityConfig extendsWebSecurityConfigurerAdapter {
  13. @AutowiredprivateMyUserService myUserService;
  14. @Overrideprotectedvoidconfigure(AuthenticationManagerBuilder auth) throwsException {
  15. /*可以将用户名密码存在内存中,也可以采用自定义Service从数据库中取 auth.inMemoryAuthentication().withUser("admin").password("12345").roles("ADMIN");
  16. auth.inMemoryAuthentication().withUser("test").password("test").roles("USER");
  17. */
  18. auth.userDetailsService(myUserService).passwordEncoder(newMyPasswordEncoder());
  19. }
  20. @Overrideprotectedvoidconfigure(HttpSecurity http) throwsException {
  21. //配置对根路径放行,其他请求拦截,对logout放行,允许表单校验,禁用CSRF http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().logout().permitAll() .and().formLogin();
  22. http.csrf().disable();
  23. }
  24. @Overridepublicvoidconfigure(WebSecurity web) throwsException {
  25. //配置忽略js、css、images静态文件 web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
  26. }
  27. }
复制代码
自定义密码加密器:
  1. packageorg.dreamtech.demo;
  2. importorg.springframework.security.authentication.encoding.Md5PasswordEncoder;
  3. importorg.springframework.security.crypto.password.PasswordEncoder;
  4. /**
  5. * 自定义密码加密器 *  * @authorXu Yiqing **/
  6. @SuppressWarnings("deprecation")
  7. publicclassMyPasswordEncoder implementsPasswordEncoder {
  8. //加密需要的盐 privatestaticfinalString SALT = "666";
  9. /**
  10. * 加密*/
  11. @OverridepublicString encode(CharSequence rawPassword) {
  12. Md5PasswordEncoder encoder = newMd5PasswordEncoder();
  13. returnencoder.encodePassword(rawPassword.toString(), SALT);
  14. }
  15. /**
  16. * 匹配*/
  17. @Overridepublicbooleanmatches(CharSequence rawPassword, String encodedPassword) {
  18. Md5PasswordEncoder encoder = newMd5PasswordEncoder();
  19. returnencoder.isPasswordValid(encodedPassword, rawPassword.toString(), SALT);
  20. }
  21. }
复制代码
Service:
  1. packageorg.dreamtech.demo;
  2. importorg.springframework.security.core.userdetails.UserDetails;
  3. importorg.springframework.security.core.userdetails.UserDetailsService;
  4. importorg.springframework.security.core.userdetails.UsernameNotFoundException;
  5. importorg.springframework.stereotype.Component;
  6. /**
  7. * 自定义服务 * @authorXu Yiqing **/
  8. @Component
  9. publicclassMyUserService implementsUserDetailsService {
  10. /**
  11. * 从DAO层根据用户名查询*/
  12. @OverridepublicUserDetails loadUserByUsername(String username) throwsUsernameNotFoundException {
  13. UserDetails userDetails = null;
  14. //DAO操作 ...... returnuserDetails;
  15. }
  16. }
复制代码
这里的Service层只是做一个示例 如果想看具体的效果,应该使用configure中注释掉的那两行进行测试
总结: Spring Security优点:功能较齐全,高度兼容Spring Spring Security缺点:体系庞大,配置繁琐,不够直观 所以,在实际开发中,人们通常选用Apache Shiro代替Spring Security
该用户未在地球留下任何的痕迹

本版积分规则

QQ|小黑屋|帮助|IT技术擎 ( 沪ICP备15054863号  

GMT+8, 2020-2-27 10:09

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表