SpringBoot整合SpringSecurity(二)认证流程

序言

上一篇文章我们做了一个简单的入门程序,我们这一篇就来简单的跟踪源码,来分析一下其中的原理,顺便了解了整个流程后更方便我们扩展去做不同的登陆。

代码请参考 https://github.com/AutismSuperman/springsecurity-example

认证流程

我们就拿上一篇的登陆来做一个分析。

用户在页面上输入 用户名密码后访问响应的登陆方法 会进入到 UsernamePasswordAuthenticationFilter在这里插入图片描述
然后会进入到attemptAuthentication 方法中。在这个方法里呢我们拿到请求中的用户名 和密码 并且构建了一个 UsernamePasswordAuthenticationToken 我们点进去看一下构建的什么
在这里插入图片描述
原来在构造方法里 setAuthenticated(false) 就代码这个 AuthenticationToken 没有进行认证。

最后返回值 返回给 AuthenticationManager 进行验证,好我们接着向下走

随后我们进入到了 ProviderManager 里 顾名思义就是各种 Provider 的管理器。

好的,下面是SpringBoot整合SpringSecurity认证流程: 1. 引入依赖 在 `pom.xml` 文件中添加 Spring Security 相关的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置安全规则 在 `application.yml` 或 `application.properties` 文件中配置安全规则: ``` spring: security: user: name: admin password: admin # 需要放行的请求路径 ignored: /css/**,/js/**,/images/** ``` 3. 创建安全配置类 创建一个继承 `WebSecurityConfigurerAdapter` 的安全配置类,并重写 `configure(HttpSecurity http)` 方法,配置安全规则。 ``` @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 配置安全规则 http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // 配置用户信息 auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}user").roles("USER"); } } ``` 在上面的代码中,`configure(HttpSecurity http)` 方法配置了三个安全规则: - `/admin/**` 路径需要 `ADMIN` 角色才能访问 - `/user/**` 路径需要 `ADMIN` 或 `USER` 角色才能访问 - 其他路径需要认证后才能访问 `configureGlobal(AuthenticationManagerBuilder auth)` 方法配置了两个用户 `admin` 和 `user`,并分别赋予了 `ADMIN` 和 `USER` 角色。 4. 启动应用程序 现在可以启动应用程序,访问 `/login` 路径进行登录,登录成功后就可以访问需要认证的路径。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值