> 文档中心 > Shiro+springboot快速入门(狂神学习,集成mybatis)

Shiro+springboot快速入门(狂神学习,集成mybatis)


Shiro+springboot菜鸟入门(狂神学习)

一:10分钟开始shiro入门

1.进入shiro官网shiiro官网
找到10分钟快速入门
在这里插入图片描述
在前往githubgithub的shiro地址
建立一个maven项目
pom.xml导入以下配置:

<dependency>     <groupId>org.apache.shiro</groupId>     <artifactId>shiro-core</artifactId>     <version>1.7.1</version> </dependency> <!-- configure logging --> <dependency>     <groupId>org.slf4j</groupId>     <artifactId>jcl-over-slf4j</artifactId>     <version>2.0.0-alpha7</version> </dependency> <dependency>     <groupId>org.apache.logging.log4j</groupId>     <artifactId>log4j-slf4j-impl</artifactId>     <version>2.17.2</version>     <scope>test</scope> </dependency> <dependency>     <groupId>org.apache.logging.log4j</groupId>     <artifactId>log4j-slf4j-impl</artifactId>     <version>2.17.2</version>     <scope>test</scope> </dependency>

在github上shiro项目中的quickstart分别找到以下文件运行
在这里插入图片描述
Quickstart.java文件

package com.example.shiro;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;/** * Simple Quickstart application showing how to use Shiro's API. * * @since 0.9 RC2 */public class Quickstart {    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);    public static void main(String[] args) { //获取当前用户对象subject // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); //通过当前用户拿到Session // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) {     log.info("Subject>=seesion [" + 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环境搭建

1.导入所需要的配置

<dependency>     <groupId>org.apache.shiro</groupId>     <artifactId>shiro-spring</artifactId>     <version>1.9.0</version> </dependency><dependency>     <groupId>log4j</groupId>     <artifactId>log4j</artifactId>     <version>1.2.7</version> </dependency>

建立创建ShiroConfig类和UserRealm类

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;@Configurationpublic class ShiroConfig {    @Bean    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); //设置安全管理器 bean.setSecurityManager(defaultWebSecurityManager); //添加shiro的内置过滤器 /*  * anon:无需认证就可以访问  * authc:必须认证了才能让问  * user: 必须拥有记住我功能才能用  * perms:拥有对某个资源的权限才能访问、  * role:拥有某个角色权限才能访问  * */ Map<String ,String > filterMap = new LinkedHashMap<>(); filterMap.put("/user/add","authc"); filterMap.put("/user/update","authc");// filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap); bean.setLoginUrl("/toLogin"); return bean;    }    //DefalutWebSecurityManager    @Bean(name = "securityManager")    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //关联UserRealm securityManager.setRealm(userRealm); return securityManager;    }    //创建realm对象,需要自定义类    @Bean(name = "userRealm")    public UserRealm userRealm(){ return new UserRealm();    }}
package com.example.demo.config;import org.apache.shiro.authc.*;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;//自定义UserRealm extends AuthorizingRealm public class UserRealm extends AuthorizingRealm {    //授权    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了授权"); return null;    }    //认证    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {// System.out.println("认证");// String name = "root";// String password = "123456";// UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;// if (!userToken.getUsername().equals(name)) {//     return null; // 抛出异常,unknownAccountException// } System.out.println("认证"); return null;    }}

controller层的方法

package com.example.demo.controller;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class MyController {    @RequestMapping({"/","/index"})    public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index";    }    @GetMapping("/user/add")    public String userAdd(){ return "user/add";    }    @GetMapping("/user/update")    public String userUpdate(){ return "user/update";    }    @GetMapping("/toLogin")    public String login(){ 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); //执行登录方法,如果没有异常说明就ok了     return "index"; } catch (UnknownAccountException e){ //用户名不存在     model.addAttribute("msg","用户名错误");     return "login"; }catch (IncorrectCredentialsException e){ //密码不存在     model.addAttribute("msg","密码错误");     return "login"; }    }}

三:shiro整合Mybatis

这是我的文件目录

在这里插入图片描述
具体的在gitees上:springboot+shiro+mybatis