概念:简单的安全框架。支持用户赋权,身份验证,授权,加密和会话。
- 基础使用
整合SpringBoot
1.导入pom包
org.apache.shiro
shiro-spring
1.8.0
2.配置三个类
○ Realm:自定义类`
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//身份验证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
if (!token.getUsername().equals("root")){
return null;//当返回为空时会自动UnknownAccountException异常
}
return new SimpleAuthenticationInfo("","123456","");//密码会和第二个参数匹配,错误IncorrectCredentialsException
}
}
○ DefaultWebSecurityManager:默认Web安全管理器
最基础的配置:将realm作为参数传入
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
○ ShiroFilterFactoryBean:shiro过滤器工厂
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);//设置安全管理器
/**
* shiro的内置过滤器
anon:无需认证就可以访问 默认
authc:必须认证了才能访问
user:必须拥有记住我功能才能访问
perms:必须拥有对某个的权限才能访问
role:拥有某个角色权限才能访问
*/
//添加shiro的内置过滤器 设置要拦截的url
Map<String,String> filterChainDefinitionMap=new LinkedHashMap<>();//拦截
filterChainDefinitionMap.put("/add","authc");// /add请求必须认证才能访问
filterChainDefinitionMap.put("/update","authc");//del必须认证才能访问
// filterChainDefinitionMap.put("user/**","authc");//支持通配符
shiroFilterFactoryBean.setLoginUrl("/login");//没有认证后跳到的页面
return shiroFilterFactoryBean;
}
3.controller使用
@PostMapping("/login")
public String login(String loginName,String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken();
usernamePasswordToken.setUsername(loginName);
usernamePasswordToken.setPassword(password.toCharArray());
try {
subject.login(usernamePasswordToken);
return "index";
}catch (UnknownAccountException e) {
/**
* 异常信息
* UnknownAccountException :用户名不存在
* IncorrectCredentialsException:密码错误
*/
System.out.println("用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
return "login";
}
}