基础篇-01.HttpBasic模式登录认证

1.HttpBasic的应用场景

HttpBasic是spring security最简单的认证方式,是一种“防君子不防小人”的登录验证,因为这种方式可以被暴力破解。

2.spring boot2.0整合spring security

maven坐标

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

3.开启HttpBasic登录认证模式

配置httpbasic模式

如果使用的Spring Boot版本为1.X版本,依赖的Security 4.X版本,那么就无需任何配置,启动项目访问则会弹出默认的httpbasic认证.

我们现在使用的是spring boot2.0版本(依赖Security 5.X版本),HttpBasic不再是默认的验证模式,在spring security 5.x默认的验证模式已经是表单模式。所以我们要使用Basic模式,需要自己调整一下。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.httpBasic()//开启httpbasic认证
      .and()
      .authorizeRequests()
      .anyRequest()
      .authenticated();//所有请求都需要登录认证才能访问
   }
}

指定用户和密码

通过application.yml指定配置用户名密码,如果不指定,在启动时后台会打印出对应的密码(默认用户是user)

spring:
    security:
      user:
        name: admin
        password: admin

4.HttpBasic原理

HttpBasic原理

  • 在Http请求中使用Authorization作为一个Header,“Basic YWtaW46YWRtaW4=“作为Header的值,发送给服务端。(注意这里使用Basic+空格+加密串),这里的加密串,使用的是BASE64进行加密,这里加密串解密后的格式是=> 账户名:密码
  • 服务器在收到这样的请求时,到达BasicAuthenticationFilter过滤器,将提取“ Authorization”的Header值,并使用用于验证用户身份的相同算法Base64进行解码。
  • 解码结果与登录验证的用户名密码匹配,匹配成功则可以继续过滤器后续的访问
posted @ 2021-06-29 18:49  linshj  阅读(535)  评论(0)    收藏  举报