手把手带你入门 Spring Security!

2年前 (2022) 程序员胖胖胖虎阿
422 0 0

Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。

相对于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比较麻烦的操作,所以,Spring Security 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,但是对于大部分项目而言,Shiro 也够用了)。

自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了 自动化配置方案,可以零配置使用 Spring Security。

因此,一般来说,常见的安全管理技术栈的组合是这样的:

  • SSM + Shiro

  • Spring Boot/Spring Cloud + Spring Security

注意,这只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。

我们来看下具体使用。

1.项目创建

在 Spring Boot 中使用 Spring Security 非常容易,引入依赖即可:

手把手带你入门 Spring Security!

pom.xml 中的 Spring Security 依赖:

  
  
  
  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-security</artifactId>

  4. </dependency>

只要加入依赖,项目的所有接口都会被自动保护起来。

2.初次体验

我们创建一个 HelloController:

  
  
  
  1. @RestController

  2. public class HelloController {

  3. @GetMapping("/hello")

  4. public String hello() {

  5. return "hello";

  6. }

  7. }

访问 /hello ,需要登录之后才能访问。

手把手带你入门 Spring Security!

当用户从浏览器发送请求访问 /hello 接口时,服务端会返回 302 响应码,让客户端重定向到 /login 页面,用户在 /login 页面登录,登陆成功之后,就会自动跳转到 /hello 接口。

另外,也可以使用 POSTMAN 来发送请求,使用 POSTMAN 发送请求时,可以将用户信息放在请求头中(这样可以避免重定向到登录页面):

手把手带你入门 Spring Security!

通过以上两种不同的登录方式,可以看出,Spring Security 支持两种不同的认证方式:

  • 可以通过 form 表单来认证

  • 可以通过 HttpBasic 来认证

3.用户名配置

默认情况下,登录的用户名是 user ,密码则是项目启动时随机生成的字符串,可以从启动的控制台日志中看到默认密码:

手把手带你入门 Spring Security!

这个随机生成的密码,每次启动时都会变。对登录的用户名/密码进行配置,有三种不同的方式:

  • 在 application.properties 中进行配置

  • 通过 Java 代码配置在内存中

  • 通过 Java 从数据库中加载

前两种比较简单,第三种代码量略大,本文就先来看看前两种,第三种后面再单独写文章介绍,也可以参考我的微人事项目。

3.1 配置文件配置用户名/密码

可以直接在 application.properties 文件中配置用户的基本信息:

  
  
  
  1. spring.security.user.name=javaboy

  2. spring.security.user.password=123

配置完成后,重启项目,就可以使用这里配置的用户名/密码登录了。

3.2 Java 配置用户名/密码

也可以在 Java 代码中配置用户名密码,首先需要我们创建一个 Spring Security 的配置类,集成自 WebSecurityConfigurerAdapter 类,如下:

  
  
  
  1. @Configuration

  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {

  3. @Override

  4. protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  5. //下面这两行配置表示在内存中配置了两个用户

  6. auth.inMemoryAuthentication()

  7. .withUser("javaboy").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")

  8. .and()

  9. .withUser("lisi").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");

  10. }

  11. @Bean

  12. PasswordEncoder passwordEncoder() {

  13. return new BCryptPasswordEncoder();

  14. }

  15. }

这里我们在 configure 方法中配置了两个用户,用户的密码都是加密之后的字符串(明文是 123),从 Spring5 开始,强制要求密码要加密,如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,但是不建议这么做,毕竟不安全。

Spring Security 中提供了 BCryptPasswordEncoder 密码编码工具,可以非常方便的实现密码的加密加盐,相同明文加密出来的结果总是不同,这样就不需要用户去额外保存 的字段了,这一点比 Shiro 要方便很多。

4.登录配置

对于登录接口,登录成功后的响应,登录失败后的响应,我们都可以在 WebSecurityConfigurerAdapter 的实现类中进行配置。例如下面这样:

  
  
  
  1. @Configuration

  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {

  3. @Autowired

  4. VerifyCodeFilter verifyCodeFilter;

  5. @Override

  6. protected void configure(HttpSecurity http) throws Exception {

  7. http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);

  8. http

  9. .authorizeRequests()//开启登录配置

  10. .antMatchers("/hello").hasRole("admin")//表示访问 /hello 这个接口,需要具备 admin 这个角色

  11. .anyRequest().authenticated()//表示剩余的其他接口,登录之后就能访问

  12. .and()

  13. .formLogin()

  14. //定义登录页面,未登录时,访问一个需要登录之后才能访问的接口,会自动跳转到该页面

  15. .loginPage("/login_p")

  16. //登录处理接口

  17. .loginProcessingUrl("/doLogin")

  18. //定义登录时,用户名的 key,默认为 username

  19. .usernameParameter("uname")

  20. //定义登录时,用户密码的 key,默认为 password

  21. .passwordParameter("passwd")

  22. //登录成功的处理器

  23. .successHandler(new AuthenticationSuccessHandler() {

  24. @Override

  25. public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {

  26. resp.setContentType("application/json;charset=utf-8");

  27. PrintWriter out = resp.getWriter();

  28. out.write("success");

  29. out.flush();

  30. }

  31. })

  32. .failureHandler(new AuthenticationFailureHandler() {

  33. @Override

  34. public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {

  35. resp.setContentType("application/json;charset=utf-8");

  36. PrintWriter out = resp.getWriter();

  37. out.write("fail");

  38. out.flush();

  39. }

  40. })

  41. .permitAll()//和表单登录相关的接口统统都直接通过

  42. .and()

  43. .logout()

  44. .logoutUrl("/logout")

  45. .logoutSuccessHandler(new LogoutSuccessHandler() {

  46. @Override

  47. public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {

  48. resp.setContentType("application/json;charset=utf-8");

  49. PrintWriter out = resp.getWriter();

  50. out.write("logout success");

  51. out.flush();

  52. }

  53. })

  54. .permitAll()

  55. .and()

  56. .httpBasic()

  57. .and()

  58. .csrf().disable();

  59. }

  60. }

我们可以在 successHandler 方法中,配置登录成功的回调,如果是前后端分离开发的话,登录成功后返回 JSON 即可,同理,failureHandler 方法中配置登录失败的回调,logoutSuccessHandler 中则配置注销成功的回调。

5.忽略拦截

如果某一个请求地址不需要拦截的话,有两种方式实现:

  • 设置该地址匿名访问

  • 直接过滤掉该地址,即该地址不走 Spring Security 过滤器链

推荐使用第二种方案,配置如下:

  
  
  
  1. @Configuration

  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {

  3. @Override

  4. public void configure(WebSecurity web) throws Exception {

  5. web.ignoring().antMatchers("/vercode");

  6. }

  7. }

Spring Security 另外一个强大之处就是它可以结合 OAuth2 ,玩出更多的花样出来,这些我们在后面的文章中再和大家细细介绍。

本文就先说到这里,有问题欢迎留言讨论。



往期精彩回顾:

MyBatis 中 @Param 注解的四种使用场景,最后一种经常被人忽略!

给数据库减负的八个思路

Spring Boot 邮件发送的 5 种姿势!

干货|最新版 Spring Boot2.1.5 教程+案例合集

2019 Java 全栈工程师进阶路线图,一定要收藏!

前后端分离时代,Java 程序员的变与不变!

手把手带你入门 Spring Security!

为了更好的和大伙切磋技术,我开通了知识星球,和大伙分享技术、分享面试经验。

松哥最新录制的 Spring Boot2.1.6 视频教程,已于上周开始连载在星球上连载,主要讲解 Spring Boot 中的方方面面+手把手带你做微人事项目:

 https://t.zsxq.com/EUNjma6

松哥的视频和博客一样,绝对的思路清晰,条理清楚,有图为证:


手把手带你入门 Spring Security!

手把手带你入门 Spring Security!

知识星球:Java 达摩院
手把手带你入门 Spring Security!

手把手带你入门 Spring Security!

手把手带你入门 Spring Security!

手把手带你入门 Spring Security!

星球上分享了海量(超过2TB)学习资源分享,项目实战资料,包含各种面试题

 https://t.zsxq.com/NNVfUzR

我做知识星球的目的和其他星主一样,就是为了帮助大家一起更好的成长,与高手拉近距离,减少差距,其实你也是高手!

手把手带你入门 Spring Security!
手把手带你入门 Spring Security!
手把手带你入门 Spring Security!
手把手带你入门 Spring Security!
手把手带你入门 Spring Security!

加入星球不满意,三天内无条件退款。

手把手带你入门 Spring Security!

手把手带你入门 Spring Security!
你点的每个在看,我都认真当成了喜欢

本文分享自微信公众号 - 江南一点雨(a_javaboy)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

版权声明:程序员胖胖胖虎阿 发表于 2022年10月5日 上午12:32。
转载请注明:手把手带你入门 Spring Security! | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...