SpringSecurty(一)初探,学会配置

「这是我参与11月更文挑战的第17天,活动详情查看:2021最后一次更文挑战」 Wireshark模块介绍

什么是Spring Security
基于Spring AOP和Servlet过滤器的安全框架,在web请求级和方法调用级处理身份确认和授权。

在Spring Framework基础上,Spring Security充分利用了依赖注入(DI)和面向切面编程(AOP)功能

核心功能
1.认证 2.验证(权限)3.攻击防护

原理技术
Filter、Servlet、Spring DI、SpringAOP

常用安全框架
主要是Spring Security和Apache Shiro
都支持1.认证 2.授权 3.加密 4.会话 5.缓存支持 6.remberMe功能 ......

  • 区别

1.Spring Security基于Spring,项目若以Spring作为基础,配合Spring Security更加方便。
Apache Shiro需要和Spring进行整合。
2.Spring Security功能比Shiro更加丰富,如安全防护
3.Spring Security社区资源更加丰富
4.Spring Security可以和Spring Boot、Spring Cloud无缝集成

1.Shiro使用配置简单
2.Shiro依赖性低,不需要任何框架、容器,独立运行。Spring Security依赖Spring容器。

依赖
spring-boot-starter-parent
spring-boot-starter-web
spring-boot-starter-security

(什么是STS开发工具)

项目启动后,添加测试controller

@RequestMapping("/hello")
@RestController
public class TestController {

    @GetMapping
    public String getWelcome() {
        return "hello";
    }
}
复制代码

启动后访问路径
会自动跳转一下路径: http://localhost:8181/login

image.png
在Spring Boot中,默认的Spring Security生效,这时的接口都被保护了,通过验证才能正常访问。
username默认为user 密码在项目启动时打印的日志

image.png
使用账号密码登录之后就可以正常访问接口了。
这个验证可以关掉吗?
可以的
启动类中添加如下代码:

 @SpringBootApplication(exclude = SecurityAutoConfiguration.class)
复制代码

image.png
自定义用户名和密码:

image.png

怎么配置多个账号信息
定义一个配置类WebSecurityConfig继承WebSecurityConfigurerAdapter

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

// 声明是个配置类
@Configuration
// 开启Spring Security
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 从内存中进行加载认证信息
         * 配置两个用户
         */
        auth.inMemoryAuthentication().withUser("user").password("123456").roles();
        auth.inMemoryAuthentication().withUser("lkk").password("123456").roles();

    }
}
复制代码

记得启动类修改

@SpringBootApplication
public class SpringSecurityApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringSecurityApplication.class, args);
	}

}
复制代码

启动项目
这时候发现项目启动成功了,但是请求接口输入账号密码后,后台报错:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
复制代码

image.png
Spring Security 5.0新增了多种加密方式,改变了密码的格式。以上报错的原因是没有指定加密方式。

加密
方式1(推荐):
在WebSecurityConfig配置类中,通过@Bean注入PasswordEncoder具体实现类

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
复制代码

给用户密码加密

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 从内存中进行加载认证信息
         * 配置两个用户
         */
        auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("123456")).roles();
        auth.inMemoryAuthentication().withUser("lkk").password(passwordEncoder().encode("123456")).roles();

    }
复制代码

重启项目后即可成功登录请求接口。

方式2:

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 从内存中进行加载认证信息
         * 配置两个用户
         */
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("123456"))
                .roles("admin");
        auth.inMemoryAuthentication()
                .withUser("lkk")
                .password(passwordEncoder().encode("123456"))
                .roles("normal");
    }
复制代码

Bcrypt:是一种跨平台的文件加密工具。使用的是Blowfish加密算法。由它加密的文件可在所有支持的操作系统和处理器上进行转移。它的口令必须是8至56个字符,并将在内部被转化为448位的密钥。

给指定用户指定角色

/**
* 添加角色
*/
auth.inMemoryAuthentication()
        .passwordEncoder(new BCryptPasswordEncoder())
        .withUser("user")
        .password("123456")
        .roles("admin");
复制代码

开启方法级安全控制
@EnableGlobalMethodSecurity注解

  • prePostEnabled:决定Spring Security前注解是否可用@PreAuthrorize@ PostAuthorize...
  • secureEnabled:决定Spring Security的保障作用@Secured是否可用
  • jsr250Enables:决定 JSR-250 annotations 注解[@RolesAllowed...] 是否可用
// 声明是个配置类
@Configuration
// 开启Spring Security
@EnableWebSecurity
// 开启方法级安全控制
// @PreAuthorize("hasAnyRole('admin')")才能生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}
复制代码

配置方法级权限控制
@PreAuthorize("hasAnyRole('admin')")

@GetMapping
@PreAuthorize("hasAnyRole('admin')")
public String getWelcome() {
    return "hello";
}
复制代码