SpringBoot项目中的安全框架Shiro和Spring Security—认证、授权等
Shiro
Shiro参考.
一个Java的安全(权限)框架,完成认证、授权、加密,会话管理,Web集成,缓存等。
- Shiro功能

- Shiro架构


Spring Security
SpringSecurity参考.
仅需在项目中引入spring-boot-starter-security模块,进行少量配置,即可实现强大安全管理!
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
三个主要类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
其两个主要目标是“认证”和“授权”(访问控制)。
package com.zzh.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才能访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限,默认会跳到登录页,需要开启登录页
// /login
http.formLogin().loginPage("/toLogin");
//开启注销功能,跳到首页
http.csrf().disable();//关闭csrf功能
http.logout().logoutSuccessUrl("/");
//开启记住我功能 cookie.默认保存两周, 自定义接收前端的参数
http.rememberMe().rememberMeParameter("remember");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常从数据库中读
//密码编码: PasswordEncoder
//springSecurity 5.0+ 新增了很多的加密码方式
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zzh").password(new BCryptPasswordEncoder().encode("123")).roles("vip2", "vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
}
}
本文对比分析了Shiro和Spring Security在SpringBoot项目中的应用。Shiro是一个Java安全框架,专注于认证、授权、加密和会话管理。而Spring Security则通过简单的引入模块和配置,即可实现强大的安全控制。Spring Security的核心类包括WebSecurityConfigurerAdapter、AuthenticationManagerBuilder和@EnableWebSecurity,主要处理认证和授权问题。

2062

被折叠的 条评论
为什么被折叠?



