shiro~
- shiro快速入门
- springboot 整合shiro
- 核心目标
- 清爽pom
- 用户认证授权认证,与数据库交互
- shiro configuration
- 核心controller 获取shiro 中的token
- 页面控制功能的隐藏和显示
https://github.com/sevenyoungairye/spring-boot-study/tree/main/springboot-shiro-07
shiro快速入门
- 什么是shiro
- apache shiro 是一个java的安全(权限)框架。
- shiro可以非常容易的开发出足够好的应用,可以在javase环境,也可用在javaee环境
- shiro可以完成 认证,授权,加密,会话管理,web继承,缓存等。
- 下载地址:http://shiro.apache.org
- shiro快速入门代码简单分析~
git来拿来的
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class QuickStart {// 日志对象private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);public static void main(String[] args) {// 创建shiro环境Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);// 获取当前的用户对象Subject currentUser = SecurityUtils.getSubject();// 获取当前sessionSession session = currentUser.getSession();// 设置keysession.setAttribute("someKey", "aValue");// 获取valueString value = (String) session.getAttribute("someKey");if (value.equals("aValue")) {log.info("Retrieved the correct value! [" + value + "]");}// let's login the current user so we can check against roles and permissions:// 是否被认证if (!currentUser.isAuthenticated()) {// token 根据用户密码 拿到令牌UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");// 记住密码token.setRememberMe(true);try {// 执行了登录操作currentUser.login(token);} catch (UnknownAccountException uae) { // 账号不存在log.info("There is no user with username of " + token.getPrincipal());} catch (IncorrectCredentialsException ice) { // 密码错误log.info("Password for account " + token.getPrincipal() + " was incorrect!");} catch (LockedAccountException lae) { // 账户锁定log.info("The account for username " + token.getPrincipal() + " is locked. " +"Please contact your administrator to unlock it.");}// ... catch more exceptions here (maybe custom ones specific to your application?catch (AuthenticationException ae) {// 最大异常//unexpected condition? error?}}// 拿到用户信息//say who they are://print their identifying principal (in this case, a username):log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");// 用户的角色//test a role:if (currentUser.hasRole("schwartz")) {log.info("May the Schwartz be with you!");} else {log.info("Hello, mere mortal.");}// 用户的普通权限//test a typed permission (not instance-level)if (currentUser.isPermitted("lightsaber:wield")) {log.info("You may use a lightsaber ring. Use it wisely.");} else {log.info("Sorry, lightsaber rings are for schwartz masters only.");}// 用户的更大的权限//a (very powerful) Instance Level permission:if (currentUser.isPermitted("winnebago:drive:eagle5")) {log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +"Here are the keys - have fun!");} else {log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");}// 注销//all done - log out!currentUser.logout();System.exit(0);}
}
springboot 整合shiro
核心目标
-
springboot 整合shiro shiro-spring
-
subject 用户
-
SecurityManager 管理所有用户
-
Realm 连接数据
-
认证 数据库匹配账号密码
-
授权 用户的角色匹配 [user:add], [user:update]用户修改和新增的权限
-
shiro与thymeleaf的整合
清爽pom
- shiro-core
<!-- shiro config.. --><dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.6.0</version></dependency><!-- configure logging --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.30</version><scope>runtime</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version><scope>runtime</scope></dependency></dependencies>
- spring 与shiro整合
<!-- thymeleaf & shiro --><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency><!-- shiro & springboot --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.6.0</version></dependency>
用户认证授权认证,与数据库交互
package cn.bitqian.config;import cn.bitqian.entity.Users;
import cn.bitqian.mapper.UsersMapper;
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.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;/*** 用户认证* @author echo lovely* @date 2020/10/27 15:58*/
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UsersMapper usersMapper;// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授权认证=> PrincipalCollection");SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();// 对user:add授权// authorizationInfo.addStringPermission("user:add");// 获取当前用户Subject subject = SecurityUtils.getSubject();Users users = (Users) subject.getPrincipal();// 进行身份认证 设置当前用户的权限authorizationInfo.addStringPermission(users.getPermission());return authorizationInfo;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("登录认证=> AuthenticationToken");// 用户名 密码认证UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;// 页面用户名String tokenUsername = userToken.getUsername();// 数据库中是否存在该用户Users users = usersMapper.findUsersByUsersName(tokenUsername);if (users == null) {return null;}SecurityUtils.getSubject().getSession().setAttribute("loginUser", users);// principal 用户认证 用户里面存在权限return new SimpleAuthenticationInfo(users, users.getUserPassword(), ""); // 密码自动验证}
}
shiro configuration
package cn.bitqian.config;import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
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.Map;/*** shiro的配置类* @author echo lovely* @date 2020/10/27 16:03*/
@Configuration
public class ShiroConfig {// 1. 自定义realm对象@Bean(name = "authorizingRealm")public AuthorizingRealm authorizingRealm() {return new UserRealm();}// 2. DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("authorizingRealm") AuthorizingRealm authorizingRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 关联UserRealmsecurityManager.setRealm(authorizingRealm);return securityManager;}// 3. ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();// 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);/*** anon 无需认证就可访问* authc 必须认证了才能访问* user 必须拥有 记住我 功能* perms 拥有对某个资源的权限* roles 角色权限*/Map<String, String> filterMap = new LinkedHashMap<>();shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);// filterMap.put("/*", "authc");// 必须认证 才可用filterMap.put("/update", "authc");filterMap.put("/add", "authc");// 必须有某个资源的权限 授权 正常的情况下,没有授权会跳转到未授权页面// user:add 和 user:update 的权限filterMap.put("/add", "perms[user:add]");filterMap.put("/update", "perms[user:update]");// 设置登录请求shiroFilterFactoryBean.setLoginUrl("login");// 没有权限 跳转到提示到页面shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");return shiroFilterFactoryBean;}@Bean // 用来整合thymeleafpublic ShiroDialect getShiroDialect() {return new ShiroDialect();}}
核心controller 获取shiro 中的token
@PostMapping(value = "/login")public String login(String username, String password, Model model) {// 设置用户名 跟 密码UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);// 获取当前用户对象Subject subject = SecurityUtils.getSubject();try {// 执行了登录操作subject.login(usernamePasswordToken);return "index";} catch (UnknownAccountException uae) { // 账号不存在model.addAttribute("msg", "账号错误");return "login";} catch (IncorrectCredentialsException ice) { // 密码错误model.addAttribute("msg", "密码错误");return "login";}}@RequestMapping(value = "/unauthorized")@ResponseBodypublic String toUnauthorized() {return "未经授权,不许访问!";}
页面控制功能的隐藏和显示
<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro.com">
<head><meta charset="UTF-8"><title>index shiro</title>
</head>
<body><p th:text="${msg}"></p><hr/><div th:if="${session.loginUser==null}"><a href="/login">login</a></div><div shiro:hasPermission="user:add"><a th:href="@{/add}">add</a></div><div shiro:hasPermission="user:update"><a th:href="@{/update}">update</a></div></body>
</html>
更多代码git clone