整合shiro和thymeleaf
需要的命名空间
xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
要使用整合我们还需要导入整合包依赖
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro --> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
之后需要去配置类配置一个新的bean
//整合ShiroDialect:用来整合shiro thymeleaf @Bean public ShiroDialect getshiroDialect(){ return new ShiroDialect(); }
完成以上步骤就可以在模版引擎上使用shiro了
前端页面内容
<!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> <span th:text="${msg}"></span> <!--从session中判断值--> <div th:if="${session.get('loginUser')==null}"> <a th:href="@{/tologin}">登录</a> </div> <a th:href="@{/logout}">注销</a> <p th:text="${msg}"></p> <hr> <!--通过shiro中的hasPermission方法,判断登录的用户是否有这个权限,有权限才显示--> <div shiro:hasPermission="user:add"> <a th:href="@{/user/add}" >add</a> </div> <div shiro:hasPermission="user:upd"> <a th:href="@{/user/upd}">update</a> </div> </body> </html>
源码
配置相关
shiroconfig
package com.hyc.config; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; @Configuration public class shrioconfig { // shirofilterfactoryBean @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); //设置安全管理器 bean.setSecurityManager(defaultWebSecurityManager); /* * 常用过滤器如下 * anon:无需认证访问 * authc:必须认证了才能访问 * user:记住我开启了,才可以用 * perms:拥有对某个资源的权限才能访问 * */ Map<String,String> filter = new LinkedHashMap(); filter.put("/user/add","perms[user:add]"); filter.put("/user/upd","perms[user:upd]"); bean.setFilterChainDefinitionMap(filter); bean.setLoginUrl("/tologin"); bean.setUnauthorizedUrl("/unauth"); return bean; } // dafultwebSecurityManager @Bean(name="SecurityManager") public DefaultWebSecurityManager getdefaultWebSecurityManager(@Qualifier("Userrealm") userrealm userrealm){ DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager(); // 关联Userrealm SecurityManager.setRealm(userrealm); return SecurityManager; } // 创建realm对象,需要自定义类 @Bean public userrealm Userrealm() { return new userrealm(); } //整合ShiroDialect:用来整合shiro thymeleaf @Bean public ShiroDialect getshiroDialect(){ return new ShiroDialect(); } }
userrealm
package com.hyc.config; import com.hyc.pojo.user; import com.hyc.service.userServiceImpl; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class userrealm extends AuthorizingRealm { @Autowired userServiceImpl userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授权=========>"); //授权信息 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //传递用户信息 Subject subject = SecurityUtils.getSubject(); user currentUser = (user) subject.getPrincipal(); //授权角色 info.addStringPermission(currentUser.getParms()); info.addRole("user:add"); info.addRole("user:upd"); return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("认证=========>"); // 获取当前的用户 Subject subject = SecurityUtils.getSubject(); // 封装用户数据 UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; user user = userService.queryUserByName(token.getUsername()); if (user==null){ return null; } Session session = subject.getSession(); session.setAttribute("loginUser",user); return new SimpleAuthenticationInfo(user,user.getPassword() ,""); } }
控制层
package com.hyc.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.session.ProxiedSession; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controller public class Mycontroller { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/upd") public String upd(){ return "user/upd"; } @RequestMapping("/tologin") public String tologin(){ return "login"; } @RequestMapping("/login") public String login(String username,String password,Model model){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username,password); try { subject.login(token); return "index"; } catch (UnknownAccountException uae) {//用户名不存在 model.addAttribute("msg","用户名不存在"); return "login"; } catch (IncorrectCredentialsException ice) {//密码不存在 model.addAttribute("msg","密码错误"); return "login"; } } @ResponseBody @RequestMapping("/unauth") public String unauth(){ return "您没有权限"; } @RequestMapping("/logout") public String logout(){ Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.removeAttribute("loginUser"); return "index"; } }
前端页面:
index
package com.hyc.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.session.ProxiedSession; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controller public class Mycontroller { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/upd") public String upd(){ return "user/upd"; } @RequestMapping("/tologin") public String tologin(){ return "login"; } @RequestMapping("/login") public String login(String username,String password,Model model){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username,password); try { subject.login(token); return "index"; } catch (UnknownAccountException uae) {//用户名不存在 model.addAttribute("msg","用户名不存在"); return "login"; } catch (IncorrectCredentialsException ice) {//密码不存在 model.addAttribute("msg","密码错误"); return "login"; } } @ResponseBody @RequestMapping("/unauth") public String unauth(){ return "您没有权限"; } @RequestMapping("/logout") public String logout(){ Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.removeAttribute("loginUser"); return "index"; } }
login
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>登陆</p> <p th:text="${msg}" style="color: red"></p> <form th:action="@{/login}"> <p> 用户名:<input type="text" name="username"></p> <p> 密码:<input type="password" name="password"></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
安全框架总结:
学习了Springsecurity和shiro之后,总结出一些学习方法
安全框架的核心思想都十分相似,授权,认证,防伪等
他们通常都有几个对象,如shiro中的subject,securityManager一样,
源码的注释写有方法使用的模版,我们可以通过下载源码去查看注释,
Springsercurity和shiro的区别,两个我个人认为,除了一个基于Spring之外功能上两者几乎一致
使用的感受
Spring Security基于Spring开发,项目中如果使用Spring作为基础,配合Spring Security做权限更加方便,而Shiro需要和Spring进行整合开发
感觉shiro没有类似于Spring Security那样的安全防护
shiro不需要基于任何框架,依赖性低
个人认为:配置的麻不麻烦关键在于项目用不用Spring,我看大神们写博客都说shrio配置要更简单一些,但是简单的上手了两个安全框架之后,我觉得使用了Spring的项目上手security要比shiro简单的多,
还有个个人感想,帮助文档的阅读能力太重要了,学习和接触新技术在没有教程的情况下,文档的阅读能力决定了你的学习上限(个人中间有一段只照着官方文档学习,十分痛苦)
以上就是安全框架简单上手的全内容啦,