1 导入Spring Security的相关依赖

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2 Spring Security认证方式之Http基本认证

2.1 实现流程

  1. Http基本认证是最简单的认证方式,不需要任何配置,导入依赖启动应用后就会弹出默认的httpBasic认证框。也相当于在实现了BrowserSecurityConfig类进行了如下配置:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //HttpBasic的alert框登录
    http.httpBasic()
    .and()
    .authorizeRequests()//对请求进行授权
    .anyRequest()//任何请求
    .authenticated();
    }
    }

    在Spring Security的默认配置中,使用用户名user,密码为控制台打印的随机码。

  2. 可以在resources配置文件中修改默认的用户名和密码,指定密码后控制台不再生成动态的随机码。

  • properties配置
  • security.user.name=user
    security.user.password=123456
  • yml配置
  • spring:
    security:
    user:
    name: user
    password: 123456

2.2 Http基本认证原理

  • 客户端向服务端请求被保护的资源,服务端向客户端请求用户名和密码,浏览器弹出登录输入框,HttpBasic模式要求传输的用户名密码使用Base64模式进行加密。客户端向服务端发起login的请求。

  • 客户端发送的Http请求中会使用Authorization作为Header,即“Basic + 空格 + Base64密码”。而Base64很容易被逆向解码,所以HttpBstic的认证方式是不安全的。

    服务器接收到请求后,到达BasicAuthenticationFilter过滤器,将提取Header值,并使用用于验证用户身份的相同算法Base64进行解码。解码结果与登录验证的用户名密码匹配,匹配成功则可以继续过滤器后续的访问。

2.3 小结

Http认证虽然配置简单,但是安全性极差,灵活性不高,无法携带cookie,所以一般应用会用安全性和灵活性更强的表单认证方式,可以通过自定义登录和验证逻辑,提高安全性。

3 表单认证

3.1 实现流程

  1. 配置使用自定义的表单登录

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    // 表单登录,而不是httpBasic
    http.formLogin()
    // 自定义登录页面
    .loginPage("login.html")
    // 指定处理登录请求的路径
    .loginProcessingUrl("/login")
    // 不限制登录页面的访问
    .permitAll()
    .and()
    .authorizeRequests()//对请求进行授权
    .anyRequest()//任何请求
    .authenticated()
    .and()
    .csrf()
    .disable();
    }
    }
  1. 自定义认证成功/失败的处理逻辑

    Spring Security中默认的成功处理逻辑定义在AbstractAuthenticationTargetUrlRequestHandler类中,在发送登录请求并认证成功后页面会跳转回到原来的访问页面,页面跳转不适用于前后端分离的系统中,因此可以自定义成功后的处理逻辑,登录后返回JSON数据。

    实现AuthenticationSuccessHandler和 AuthenticationFailureHandle类中的处理方法。

    @Component("customAuthenticationSuccessHandler")
    public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    httpServletResponse.setContentType("application/json;charset=UTF-8");
    httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
    }
    }
    @Component("customAuthenticationFailureHandler")
    public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
    log.info("登录失败");
    httpServletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    httpServletResponse.setContentType("application/json;charset=UTF-8");
    httpServletResponse.getWriter().write(e.getMessage());
    }
    }

    在WebSecurity配置文件中配置自定义的处理器

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
// 表单登录,而不是httpBasic
http.formLogin()
// 自定义登录页面
.loginPage("login.html")
// 不限制登录页面的访问
.permitAll()
// 自定义认证后的处理器
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler)
.and()
.authorizeRequests()//对请求进行授权
.anyRequest()//任何请求
.authenticated()
.and()
.csrf()
.disable();

}
}

3.2 关于HttpSecurity

在配置文件中使用HttpSecurity进行HTTP请求安全策略的配置,HttpSecurity被设计为链式调用,执行每个方法会返回一个预期的上下文,用于连续调用,其中:

  • authorizeRequests()相当于XML中的<intercept-url>标签,它返回一个URL拦截注册器,可以调用它提供的anyRequest()、antMatchers()、regexMatchers()等方法来匹配系统的URL,并为它指定安全策略。

  • formLogin()相当于XML中的<form-login>标签,声明了需要Spring Security提供的表单认证方式,返回对应的配置器,loginPage()用于指定自定义的登录页面。Spring Security会为该登录页注册一个POST路由用于接收登录请求。

  • httpBasic()相当于XML中的<http-basic>标签

  • csrf()相当于XML中的<csrf>标签,提供了跨站请求伪造防护功能,继承WebSecurityConfigurerAdapter会默认开启csrf()方法。

使用and()方法可以结束当前标签,上下文会回到HttpSecurity,否则链式调用的上下文会自动进入对应的标签域。

【Spring Security】1.快速入门的更多相关文章

  1. Spring Boot:快速入门教程

    什么是Spring Boot? Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人 ...

  2. Spring MVC 教程,快速入门,深入分析

    http://elf8848.iteye.com/blog/875830/ Spring MVC 教程,快速入门,深入分析 博客分类: SPRING Spring MVC 教程快速入门  资源下载: ...

  3. Spring Boot【快速入门】简单案例

    Spring Boot[快速入门]   Spring Boot 概述 Build Anything with Spring Boot:Spring Boot is the starting point ...

  4. Spring Security极简入门三部曲(上篇)

    目录 Spring Security极简入门三部曲(上篇) 写在前面 为什么要用Spring Security 数据库设计 demo时刻 核心代码讲解 小结 Spring Security极简入门三部 ...

  5. Spring Security极简入门三部曲(中篇)

    目录 Spring Security极简入门三部曲(中篇) 验证流程 Authentication接口 过滤器链 AuthenticationProvider接口: demo时刻 代码讲解 小结 Sp ...

  6. springboot集成spring security安全框架入门篇

    一. :spring security的简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下 ...

  7. Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】

    Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...

  8. 笔记:Spring Cloud Zuul 快速入门

    Spring Cloud Zuul 实现了路由规则与实例的维护问题,通过 Spring Cloud Eureka 进行整合,将自身注册为 Eureka 服务治理下的应用,同时从 Eureka 中获取了 ...

  9. Spring Cloud Zuul 快速入门

    Spring Cloud Zuul 实现了路由规则与实例的维护问题,通过 Spring Cloud Eureka 进行整合,将自身注册为 Eureka 服务治理下的应用,同时从 Eureka 中获取了 ...

  10. Spring MVC 教程,快速入门,深入分析[1-11]

    资源下载: Spring_MVC_教程_快速入门_深入分析V1.1.pdf SpringMVC核心配置文件示例.rar     作者:赵磊 博客:http://elf8848.iteye.com   ...

随机推荐

  1. 使用 JS 开发 Github Actions 实现自动部署前后台项目到自己服务器

    不想看前面这么多废话的可以直接跳到具体实现 Github Actions 是什么? 说到 Github Actions 不得不提一下. 持续集成(continuous integration):高质量 ...

  2. P1092 虫食算(洛谷)

    今天做了一道题,我之前吹牛的时候曾经说:“这个题我觉得深搜剪枝一下就可以了.”. 我觉得我之前说的没错“这个题深搜剪枝亿下,再加点玄学就可以了!” 题目描述 所谓虫食算,就是原先的算式中有一部分被虫子 ...

  3. tineMCE 踩坑:images_upload_handler

    tineMCE 的官方示例提供了前端上传图片方法 images_upload_handler 的写法. 但官方写的有点问题,上传会报错. 不过修改也很简单: images_upload_handler ...

  4. 给网站接入CloudFlare的CDN

    注册并登录咱的CF账号 emmmmm 添加咱的域名 食用DNS

  5. accpet和connect设置超时

    三次握手 TCP连接建立的开始是三次握手,通过三次交互确认连接成功,在客户端调用connect时,客户端发送sync消息给服务端,服务端收到sync消息后,返回一个ack+sync,并等待ack,客户 ...

  6. Webpack前世今生

    在正式介绍Webpack之前,先给大家说明一下前端为什么需要模块化 1.为什么需要模块化 1.1JS原始功能 在网页开发的早期,js制作作为一种脚本语言,做一些简单的表单验证或动画实现等,那个时候代码 ...

  7. Linux中profile和bashrc的区别

    profile主要设置系统环境参数(可类比为Windows的系统环境变量),如$PATH /etc/profile ~/.bash_profile bashrc主要用来设置bash命令,如命令别名,a ...

  8. Vue+ElementUI搭建一个后台管理框架

    参考 :https://www.cnblogs.com/taotaozhuanyong/p/11903750.html https://gitee.com/qianhongtang-share/vue ...

  9. 《Python编程初学者指南》高清PDF版|百度网盘免费下载|Python基础

    <Python编程初学者指南>|百度网盘免费下载| 提取码:03b1 内容简介 Python是一种解释型.面向对象.动态数据类型的高级程序设计语言.Python可以用于很多的领域,从科学计 ...

  10. 想学Python不知道从哪里开始学?|百度网盘免费下载| 这本入门书了解下

    百度网盘免费下载:编程小白的第一本 Python 入门书 提取码:s0pc Python是什么 Python是一种计算机程序设计语言,由吉多·范罗苏姆创造,第一版发布于1991年,可以视之为一种改良的 ...