springboot-权限控制shiro(二)

  • 2019 年 10 月 3 日
  • 筆記

1. ????

?1?????????????????????????????????springboot??????shiro?demo??????????????????????????????

?2??????springboot??shrio?springboot-????shiro????????????????springboot?shiro????????springboot-????shiro(?)?

2. ????

2.1 ????

2.1.1 ???

2.1.2 ????

shiro?demo???????????

?1?1?pom???????jar??

?2?2????resources??????????6??????

?3?3??????????????shiro????

2.1.3 shiro ?????

?1??????
anon?????????????
authc: ???????????
user?????rememberMe??????
?2??????
perms: ??????????
roles : ??????????

??????anon?authc?????perms???????????shiro?????????????????

2.2 pom??

<?xml version="1.0" encoding="UTF-8"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>      <parent>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-parent</artifactId>          <version>2.1.6.RELEASE</version>          <relativePath/> <!-- lookup parent from repository -->      </parent>      <groupId>com.laowang</groupId>      <artifactId>lwshiro</artifactId>      <version>0.0.1-SNAPSHOT</version>      <name>lwshiro</name>      <description>Demo project for Spring Boot</description>      <properties>          <java.version>1.8</java.version>      </properties>        <dependencies>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-web</artifactId>          </dependency>            <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-test</artifactId>              <scope>test</scope>          </dependency>            <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-thymeleaf</artifactId>          </dependency>          <dependency>              <groupId>org.apache.shiro</groupId>              <artifactId>shiro-spring</artifactId>              <version>1.4.0</version>          </dependency>      </dependencies>        <build>          <plugins>              <plugin>                  <groupId>org.springframework.boot</groupId>                  <artifactId>spring-boot-maven-plugin</artifactId>              </plugin>          </plugins>      </build>    </project>  

???

?????gav

1. spring-boot-starter-thymeleaf ---???????2.2?
2. shiro-spring  -----shiro???

2.3 resource????????

2.3.1 application.properties
server.port=8000  spring.thymeleaf.cache=false

???????????8000?cache=false???????????????????

2.3.2 ????

?1?index.html

<!DOCTYPE html>  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>??????</title>  </head>  <body>  <h3>??????</h3>    ??????<span th:text="${session.userName}"></span>?<a href="/user/logout">??</a>    <hr/>  <span>  <a href="/page/toa">??1</a><br/>  </span>  <span >  <a href="/page/tob">??2</a><br/>  </span>  <span >  <a href="/page/toc">??3</a><br/>  </span>    </body>  </html>

?2?login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>????</title>  </head>  <body>  <h3>??</h3>  <font color="red" th:text="${msg}"></font>    <form method="post" action="/user/login">    ????<input type="text" name="name"/><br/>    ???<input type="password" name="password"/><br/>    <input type="submit" value="??">  </form>  </body>  </html>

?3?unauth.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>???????</title>  </head>  <body>  i'm ????,?????????  </body>  </html>

?4?a.html? b.html? c.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>i'm ????,??a</title>  </head>  <body>  i'm ????,??a  </body>  </html>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>i'm ????,??b</title>  </head>  <body>  i'm ????,??b  </body>  </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>i'm ????,??c</title>  </head>  <body>  i'm ????,??c  </body>  </html>

??? ?????????????????????????????? th????thymeleaf???????????

2.4 java?

2.4.1 ????LwshiroApplication?
package com.laowang.lwshiro;    import org.springframework.boot.SpringApplication;  import org.springframework.boot.autoconfigure.SpringBootApplication;    @SpringBootApplication  public class LwshiroApplication {        public static void main(String[] args) {          SpringApplication.run(LwshiroApplication.class, args);      }    }  

??? springboot??????

2.4.2 ??????UserController?
package com.laowang.lwshiro.controller;      import org.apache.shiro.SecurityUtils;  import org.apache.shiro.authc.AuthenticationToken;  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.RequestMapping;    import javax.servlet.http.HttpServletRequest;    /**   * ?????   * @auther: ????   * @date: 2019/7/30   */  @Controller  @RequestMapping("/user")  public class UserController {      @RequestMapping("/login")      public String login(User user, HttpServletRequest request,                          Model model) {            Subject subject = SecurityUtils.getSubject();          AuthenticationToken token = new UsernamePasswordToken(user.getName(),                  user.getPassword());            try {              subject.login(token);              User tuser = (User)subject.getPrincipal();              request.getSession().setAttribute("userName",tuser.getName());                return "redirect:/index";          } catch (UnknownAccountException e) {              model.addAttribute("msg", "i'm ????,??????");              return "login";          } catch (IncorrectCredentialsException e) {              model.addAttribute("msg", "i'm ????,????");              return "login";          }      }        /**       * i'm ?????????       */      @RequestMapping("/logout")      public String logout(){          Subject subject = SecurityUtils.getSubject();          subject.logout(); //shiro????session?????          return "redirect:/toLogin";      }    }  

???

?????3???

 Subject subject = SecurityUtils.getSubject();       -----------#1          AuthenticationToken token = new UsernamePasswordToken(user.getName(),                  user.getPassword());        ---------#2            try {              subject.login(token);            ----------#3

?1???????????subject?????????

?2???????????????????token??

?3????????????login???

?4???MyRealm??doGetAuthenticationInfo?????????token???????????????????????

2.4.3 ??????User)
package com.laowang.lwshiro.controller;    import java.io.Serializable;    /**   * ?????   * @auther: ????   * @date: 2019/7/30   */  public class User implements Serializable{        private Integer id;      private String name;      private String password;      public Integer getId() {          return id;      }      public void setId(Integer id) {          this.id = id;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public String getPassword() {          return password;      }      public void setPassword(String password) {          this.password = password;      }      @Override      public String toString() {          return "User [id=" + id + ", name=" + name + ", password=" + password + "]";      }      }  

??? ?????

2.4.4 ????(PageController)
package com.laowang.lwshiro.controller;    import org.springframework.stereotype.Controller;  import org.springframework.web.bind.annotation.RequestMapping;    /**   * ????   * @auther: ????   * @date: 2019/7/30   */  @Controller  @RequestMapping("/page")  public class PageController {        /**       * i'm ????       */      @RequestMapping("/toa")      public String toAdd(){          return "page/a";      }      /**       * i'm ????       */      @RequestMapping("/tob")      public String toList(){          return "page/b";      }      /**       * i'm ????       */      @RequestMapping("/toc")      public String toUpdate(){          return "page/c";      }  }  

??? ?????????????

2.4.5 ????(MainController)
package com.laowang.lwshiro.controller;    import org.springframework.stereotype.Controller;  import org.springframework.web.bind.annotation.RequestMapping;    /**   *  ????   * @auther: ????   * @date: 2019/7/30   */  @Controller  @RequestMapping("/")  public class MainController {      /**       * i'm ????       */      @RequestMapping("/index")      public String index(){          return "index";      }      /**       * i'm ????       */      @RequestMapping("/toLogin")      public String toLogin(){          return "login";      }      /**       * i'm ????       */      @RequestMapping("/unAuth")      public String unAuth(){          return "unauth";      }    }

??? ?????????????

2.4.6 shiro????(ShiroConfig)
package com.laowang.lwshiro.config;    import org.apache.shiro.spring.web.ShiroFilterFactoryBean;  import org.apache.shiro.web.mgt.DefaultWebSecurityManager;  import org.springframework.context.annotation.Bean;  import org.springframework.context.annotation.Configuration;    import java.util.LinkedHashMap;  import java.util.Map;    /**   *  shiro????   * @auther: ????   * @date: 2019/7/30   */  @Configuration  public class ShiroConfig {        /**       * i'm ????       */      @Bean      public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {            ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();          shiroFilterFactoryBean.setSecurityManager(securityManager);            Map<String, String> filterMap = new LinkedHashMap<>();          //??          filterMap.put("/page/toa", "anon");          filterMap.put("/user/login", "anon");            //?????  //        filterMap.put("/page/toa", "perms[toa]");          filterMap.put("/page/tob", "perms[tob]");          filterMap.put("/page/toc", "perms");            filterMap.put("/**", "authc");            shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);            shiroFilterFactoryBean.setLoginUrl("/toLogin");          shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");            return shiroFilterFactoryBean;        }        /**       * i'm ????       */      @Bean      public DefaultWebSecurityManager getSecurityManager(MyRealm myRealm) {          DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();          defaultWebSecurityManager.setRealm(myRealm);          return defaultWebSecurityManager;      }        /**       * i'm ????       */      @Bean      public MyRealm getMyReal() {          MyRealm myReal = new MyRealm();          return myReal;      }  }  

???

???shiro?????????????????????bean?????

?1?getShiroFilterFactoryBean??bean?????????????????????????????????????bean???????????????????????????

?2?getSecurityManager???????? Subject subject = SecurityUtils.getSubject()???????????MyRealm???????shiro?????

?3?getMyReal ??bean?????MyRealm??

2.4.7 shiro???(MyRealm)
package com.laowang.lwshiro.config;    import com.laowang.lwshiro.controller.User;  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;    /**   *  shiro???   * @auther: ????   * @date: 2019/7/30   */  public class MyRealm extends AuthorizingRealm {      /**       * i'm ????       */      @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {          SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();          info.addStringPermission("toa");          info.addStringPermission("toc");          return info;      }      /**       * i'm ????       */      @Override      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {          UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;          String  name ="laowang";          String  password="123";            if (!token.getUsername().equalsIgnoreCase(name)) {              return null;          }          User tuser = new User();          tuser.setName(name);          tuser.setPassword(password);          return  new SimpleAuthenticationInfo(tuser,tuser.getPassword(),"");      }  }  

??

?????????????????????????

?1? doGetAuthorizationInfo????????????????????????????????????????????????????unauth???

?2?doGetAuthenticationInfo????????????????subject.login???????????????????????????????????????SimpleAuthenticationInfo??shiro???????????????????????

2.5 ??

2.5.1 ???

?????http://localhost:8000

2.5.2 ??

?????laowang????123

?1?????

?2?????

2.5.3 ????

?myrealm?????????a???c?????????b?????????????????????????????????????????

    @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {          SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();          info.addStringPermission("toa");          info.addStringPermission("toc");          return info;      }

?1?????a

?2?????b


I’m ?????????????????????????????????????????????