经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot整合Spring Security使用Demo
来源:cnblogs  作者:一清  时间:2019/4/23 10:44:03  对本文有异议

https://start.spring.io/ 生成SpringBoot项目

 

pom文件应该是我这样的:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>1.5.20.RELEASE</version>
  10. <relativePath /> <!-- lookup parent from repository -->
  11. </parent>
  12. <groupId>org.dreamtech</groupId>
  13. <artifactId>demo</artifactId>
  14. <version>0.0.1-SNAPSHOT</version>
  15. <packaging>war</packaging>
  16. <name>demo</name>
  17. <description>Demo project for Spring Security</description>
  18.  
  19. <properties>
  20. <java.version>1.8</java.version>
  21. </properties>
  22.  
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-security</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32. <!-- 在IDEA中如果项目运行失败,注释掉这一项即可 -->
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-tomcat</artifactId>
  36. <scope>provided</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.security</groupId>
  45. <artifactId>spring-security-test</artifactId>
  46. <scope>test</scope>
  47. </dependency>
  48. </dependencies>
  49.  
  50. <build>
  51. <plugins>
  52. <plugin>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-maven-plugin</artifactId>
  55. </plugin>
  56. </plugins>
  57. </build>
  58.  
  59. </project>

 

Controller:

  1. package org.dreamtech.demo;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.security.access.prepost.PreAuthorize;
  6. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * Spring Boot启动类
  11. * @author Xu Yiqing
  12. *
  13. */
  14. @SpringBootApplication
  15. @RestController
  16. @EnableAutoConfiguration
  17. @EnableGlobalMethodSecurity(prePostEnabled = true)
  18. public class DemoApplication {
  19. public static void main(String[] args) {
  20. SpringApplication.run(DemoApplication.class, args);
  21. }
  22. /**
  23. * 根目录,所有人都可以访问
  24. * @return
  25. */
  26. @RequestMapping("/")
  27. public String helloSpringBoot() {
  28. return "hello spring boot";
  29. }
  30. /**
  31. * 只有经过身份认证后才可以访问
  32. * @return
  33. */
  34. @RequestMapping("/hello")
  35. public String helloWorld() {
  36. return "hello world";
  37. }
  38. /**
  39. * 经过身份认证且身份必须是ADMIN才可以访问,并且是在方法执行前进行验证
  40. * @return
  41. */
  42. @PreAuthorize("hasRole('ROLE_ADMIN')")
  43. @RequestMapping("/role")
  44. public String role() {
  45. return "admin auth";
  46. }
  47. }

 

Spring Security配置文件:

  1. package org.dreamtech.demo;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. /**
  10. * Spring Security配置文件
  11. * @author Xu Yiqing
  12. *
  13. */
  14. @Configuration
  15. @EnableWebSecurity
  16. public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
  17. @Autowired
  18. private MyUserService myUserService;
  19. @Override
  20. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  21. /* 可以将用户名密码存在内存中,也可以采用自定义Service从数据库中取
  22. auth.inMemoryAuthentication().withUser("admin").password("12345").roles("ADMIN");
  23. auth.inMemoryAuthentication().withUser("test").password("test").roles("USER");
  24. */
  25. auth.userDetailsService(myUserService).passwordEncoder(new MyPasswordEncoder());
  26. }
  27. @Override
  28. protected void configure(HttpSecurity http) throws Exception {
  29. // 配置对根路径放行,其他请求拦截,对logout放行,允许表单校验,禁用CSRF
  30. http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().logout().permitAll()
  31. .and().formLogin();
  32. http.csrf().disable();
  33. }
  34. @Override
  35. public void configure(WebSecurity web) throws Exception {
  36. // 配置忽略js、css、images静态文件
  37. web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
  38. }
  39. }

 

自定义密码加密器:

  1. package org.dreamtech.demo;
  2. import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
  3. import org.springframework.security.crypto.password.PasswordEncoder;
  4. /**
  5. * 自定义密码加密器
  6. *
  7. * @author Xu Yiqing
  8. *
  9. */
  10. @SuppressWarnings("deprecation")
  11. public class MyPasswordEncoder implements PasswordEncoder {
  12. // 加密需要的盐
  13. private static final String SALT = "666";
  14. /**
  15. * 加密
  16. */
  17. @Override
  18. public String encode(CharSequence rawPassword) {
  19. Md5PasswordEncoder encoder = new Md5PasswordEncoder();
  20. return encoder.encodePassword(rawPassword.toString(), SALT);
  21. }
  22. /**
  23. * 匹配
  24. */
  25. @Override
  26. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  27. Md5PasswordEncoder encoder = new Md5PasswordEncoder();
  28. return encoder.isPasswordValid(encodedPassword, rawPassword.toString(), SALT);
  29. }
  30. }

 

Service:

  1. package org.dreamtech.demo;
  2. import org.springframework.security.core.userdetails.UserDetails;
  3. import org.springframework.security.core.userdetails.UserDetailsService;
  4. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * 自定义服务
  8. * @author Xu Yiqing
  9. *
  10. */
  11. @Component
  12. public class MyUserService implements UserDetailsService {
  13. /**
  14. * 从DAO层根据用户名查询
  15. */
  16. @Override
  17. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  18. UserDetails userDetails = null;
  19. // DAO操作 ......
  20. return userDetails;
  21. }
  22. }

这里的Service层只是做一个示例

如果想看具体的效果,应该使用configure中注释掉的那两行进行测试

总结:

Spring Security优点:功能较齐全,高度兼容Spring

Spring Security缺点:体系庞大,配置繁琐,不够直观

所以,在实际开发中,人们通常选用Apache Shiro代替Spring Security

原文链接:http://www.cnblogs.com/xuyiqing/p/10754798.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号