Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 Spring Security 做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。
首先在Spring中使用shiro首先要导入shiro的依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.0</version>
</dependency>
其次就是对shiro的一些主要功能进行编写
我们在springboot中如果不适用配置文件的话就是创建一个config的文件夹进行存放我们的自己设置的一些管理。例如shiro、国际化、.....
创建realm对象,需要自定义类:
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
DefaultWebSecurityManager:
@Bean
public DefaultWebSecurityManager getDefaultWebSessionManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
shiroFilterFactoryBean;
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSessionManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
* anon:无需认证就可以访问
* authc:必须认证了才能访问
* user:拥有记住我 功能才能使用
* perms:拥有对某个资源的权限才能访问
* role:拥有这个角色权限才能访问
* */
// filterMap.put("/user/add","authc")
//filterMap.put("/user/update","authc")
//拦截
System.out.println("----------------------");
//跳转到没有登录的页面
bean.setLoginUrl("/toLogin");
//跳转到没有授权的页面
bean.setUnauthorizedUrl("/noauth");
Map<String,String> filterMap=new LinkedHashMap<>();
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
return bean;
}
自定义类的编写
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Autowired
UserServiceImpl userService;//查询数据库中的数据
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");
//拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User principal = (User)subject.getPrincipal();//拿导User对象
info.addStringPermission(principal.getPerms());//设置当前用户的权限
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
//用户名,密码 数据库中取
UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken;
User user = userService.queryUserName(userToken.getUsername());
Subject subject1 = SecurityUtils.getSubject();
Session session = subject1.getSession();
session.setAttribute("loginUser",user);
if(user==null){//没有这个人
return null;//UnknownAccountException
}
//密码认证 shiro自己做
//可以加密: MD5 MD5盐值加密
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
前端页面
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<div th:if="${session.loginUser==null}">
<p><a th:href="@{/toLogin}">登录</a></p></div>
<p th:text="${msg}"></p>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a></div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" th:method="post">
用户名:<input type="text" name="username">
密码: <input type="text" name="password">
<input type="submit">
</form>
</body>
</html>
这就是主要的配置,其次就是对Controller的编写,以及service和dao、pojo这些就自己写就可以了
Controller
@Controller
public class MyController {
@RequestMapping({"/","index"})
public String toIndex(Model model){
model.addAttribute("msg","Hello shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
System.out.println("111111111111111111111111");
System.out.println(username);
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录的方法,如果没有异常就说明
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
//未授权页面
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未授权无法访问此页面";
}
}
pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
dao
@Repository
@Mapper
public interface UserMapper {
public User queryUserName(String name);
}
serviceimpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryUserName(String name) {
return userMapper.queryUserName(name);
}
}
service
public interface UserService {
public User queryUserName(String name);
}
这样基本就可以实现一个简单的用户权限控制.