Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
SpringSecurity是一个功能强大且高度定制的身份验证和访问控制框架。这是保护基于Spring的应用程序的事实上的标准。
spring security 的核心功能主要包括:
认证: Authentication (你是谁)
认证是否为合法用户,简单的说是登录。一般为匹对用户名和密码,即认证成功
授权 Authorization (你能干什么)
授权管理,是在已认证的前提下。用户在认证后,根据用户的不同权限,开放不同的资源。
添加依赖
org.springframework.boot
spring-boot-starter-parent
2.3.7.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-security
org.projectlombok
lombok
1.18.22
@SpringBootApplication
public class BootApp {
public static void main(String[] args) {
SpringApplication.run(BootApp.class, args);
}
}浏览器输入 http://127.0.0.1:8080/get
当我们项目依赖 spring-boot-starter-security 的启动stater,则认证默认生效,且springSecurity提供了默认的登录页面,只有输入正确的输入用户\密码后才可以访问系统资源.
用户名默认:user
密码:项目启动时在控制台输出随机密码
再次启动,就能使用 user 和密码 123 登录了
Spring Security核心就是一组过滤器链,内部包含了提供各种功能的过滤器,项目启动后将会自动配置。
上图只是列出了常见的过滤器
1.UsernamePasswordAuthenticationFilter 用来处理表单用户和密码登录。
2FilterSecurityInterceptor 获取所配置资源访问的授权信息,决定其是否有权限。
3.ExceptionTranslationFilter 用来捕获FilterSecurityInterceptor 抛出的异常,比如,没有登录,则引导到登录页面Authentication:封装了用户登录的信息
AuthenticationManager:定义了认证Authentication的方法
userDetailService接口:定义了根据用户名查询用户信息的方法
UserDetail: 通过userDetailService的查询用户的方法后,封装成UserDetail 对象返回,然后将对象封装到Authentication中
spring把 用户的信息会被封装在UserDetailService,用户需要实现该接口,处理自己的业务逻辑
@Component
public class MyUserDetailService implements UserDetailsService {
@Autowired
PasswordEncoder passwordEncoder;//密码处理类
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
String pwd =passwordEncoder.encode("123456"); //password 应该从数据库获取
//第三个参数:该用户的权限。--正常从数据库获取
return new User(s,pwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}根据用户输入的用户名,获取用户的信息(比如从数据库中获取),进行校验,如果通过则封装到session中,如果没有该用户获取校验不通过,侧抛出异常。
@Configuration
public class MySecurityConfig {
//注册PasswordEncoder
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Title
用户登录
注意:name和password 必须是 username 和 password
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter{
//注册PasswordEncoder
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login.html")//登录页面地址
.loginProcessingUrl("/user/auth")//登录页面提交的地址
.and()
.authorizeRequests()
.antMatchers("/login.html").permitAll()//放行的页面
.anyRequest().authenticated().and().csrf().disable();
}
}输入正确的密码,就可以访问系统的资源了,至此,我们应该对spring-security的认证应该有了一定的认识。
| 留言与评论(共有 0 条评论) “” |