Shiro
Shiro
springboot使用shiro完成授权和认证
pom.xml中引入shiro的依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.5.3</version>
</dependency>
thymeleaf与shiro整合
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
新建一个config文件夹,编写ShiroConfig类配置Shiro
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//添加shiro的内置过滤器
/*
anno: 无需认证就可访问
authc:必须认证才能访问
user:必须拥有 记住我 功能才能使用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截
Map<String,String> filterMap = new LinkedHashMap<>();
//授权
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
return shiroFilterFactoryBean;
}
//DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//关联UserRealm
defaultWebSecurityManager.setRealm(userRealm);;
return defaultWebSecurityManager;
}
//创建 realm 对象,需要自定义
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合ShiroDialect和thymelead
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm
// 自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了===>授权");
//获取当前对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
System.out.println("执行了===>认证");
// 用户名密码 数据库取
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
User user = userService.getUserByName(userToken.getUsername());
if (user==null) {
return null;
}
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
// 密码认证
// ByteSource credentiasSalt = ByteSource.Util.bytes(user.getName());
return new SimpleAuthenticationInfo(user,user.getPwd(), user.getName());
}
}
再定义一个controller
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,shiro");
return "index";
}
@GetMapping("/user/add")
public String add(){
return "user/add";
}
@GetMapping("/user/update")
public String update(){
return "user/update";
}
@GetMapping("/toLogin")
public String toLogin(){
return "login";
}
@PostMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
//执行登录方法,如果无异常说明OK
try {
subject.login(usernamePasswordToken);
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 "未经授权,无法访问";
}
}
templates下新建user文件夹,写一个add.html和update.html内容随意
在templates的根目录下新建index.html和login.html
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<div th:if="session.loginUser==null">
<p>
<a th:href="@{/toLogin}">登录</a>
</p>
</div>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
</br>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" method="post">
用户名:<input type="text" name="username">
<br/>
密码:<input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
本文系作者 @jiang 原创发布在 IT梦。未经许可,禁止转载。
牛牛牛
@Kristen: 雀食牛pi