Springboot集成shiro

1、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>

    <groupId>com.gupaoedu</groupId>
    <artifactId>springboot-Base-shiro</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.15.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.14</version>
        </dependency>
        <!--shiro的依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--shiro与thymeleaf的整合依赖-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>


</project>

2、自定义的realm


public class AuthcRealm extends AuthorizingRealm {

    @Autowired
    private IUserservice userservice;

    /**
     * 认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        System.out.println("认证开始"+username);
        User user = new User();
        user.setUsername(username);
        List<User> userList = userservice.query(user);
        System.out.println("认证查询到的list"+userList);
        if(userList == null || userList.size() <1){
            return  null;
        }
        user = userList.get(0);
        return new SimpleAuthenticationInfo(user,user.getPassword(),new SimpleByteSource("aaa"),"authcRealm");
    }


    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println("授权的账号"+user.getUsername());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("role1");
        return info;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("1234","aaa",1024);
        System.out.println(md5Hash);
    }
}

3、shiro的配置类

@Configuration
public class ShiroConfig {


    // 散列算法
    private String hashAlgorithmName = "md5";
    // 迭代次数
    private Integer hashIterations = 1024;

    /**
     * 获取凭证匹配器
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName(hashAlgorithmName);
        matcher.setHashIterations(hashIterations);
        return matcher;
    }
    /**
     * 获取自定义的Realm
     * @return
     */
    @Bean
    public AuthcRealm authcRealm(HashedCredentialsMatcher matcher){
        AuthcRealm realm = new AuthcRealm();
        realm.setCredentialsMatcher(matcher);
        return  realm;
    }

    /**
     *  获取SecurityManager对象
     * @param realm
     * @return
     */
    @Bean
    public SecurityManager securityManager(AuthcRealm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm);
        return manager;
    }

    /**
     * 注册ShiroFilterFactoryBean
     * @param manager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){
        ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
        filter.setSecurityManager(manager);
        filter.setLoginUrl("/login.do");
        filter.setSuccessUrl("/success.html");
        filter.setUnauthorizedUrl("/refuse.html");
        // 设置过滤器链
        Map<String,String> map = new HashMap<>();
        map.put("/css/*","anon");
        map.put("/js/**","anon");
        map.put("/img/**","anon");
        map.put("/js/**","anon");
        map.put("/login.do","authc");
        map.put("/login","authc");
        map.put("/**","authc");
        filter.setFilterChainDefinitionMap(map);
        return filter;
    }

    /**
     * 开始Shiro 注解授权操作
     * @param manager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager manager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(manager);
        return advisor;
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }





}

4、认证处理类


@Controller
public class AuthcController {

    @RequestMapping("/login.do")
    public String login(HttpServletRequest request){
        //认证失败的异常信息
        Object attribute = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        System.out.println("认证失败的信息"+attribute);
        return "login";

    }

    @RequestMapping("/logout.do")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

}

5、授权业务类

@Controller
public class UserController {

    @Autowired
    private IUserservice userservice;

    @RequiresRoles(value = {"role1","role2"},logical = Logical.OR)
    @RequestMapping("/query")
    public String query(Model model){
        User user = new User();
        model.addAttribute("list",userservice.query(user));
        return "user";
    }
    @RequiresRoles(value = {"role2","role3"},logical = Logical.OR)
    @RequestMapping("/query2")
    public String query2(Model model){
        User user = new User();
        model.addAttribute("list",userservice.query(user));
        return "user";
    }
//
//    @RequestMapping("/{page}")
//    public String showPage(@PathVariable String page){
//        return page;
//    }
}

6、异常处理类

@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        System.out.println("全局的自定义异常出现。。。");
        ModelAndView modelAndView = new ModelAndView();
        if(e instanceof NullPointerException){
            modelAndView.setViewName("error1");
            modelAndView.addObject("errorMsg","空指针异常");
        }else if(e instanceof IndexOutOfBoundsException){
            modelAndView.setViewName("error2");
            modelAndView.addObject("errorMsg","数组越界异常");
        }else if(e instanceof AuthorizationException){
            modelAndView.setViewName("error2");
            modelAndView.addObject("errorMsg","无访问权限");
        }else{
            modelAndView.setViewName("error");
            modelAndView.addObject("errorMsg","其他异常");

        }
        return modelAndView;
    }
}

7、shiro与thymeleaf的整合

@SpringBootApplication
@MapperScan("com.gupaoedu.mapper")
public class StartAPP {

    public static void main(String[] args) {
        SpringApplication.run(StartAPP.class,args);
    }



    // 添加一个Thymeleaf的模板
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }


}

8、页面

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录管理</h1>
<form th:action="@{/login.do}" method="post">
    <label>账号:</label><input type="text" name="username"><br>
    <label>密码:</label><input type="password" name="password"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
</head>
<body>
<h1>用户管理</h1>
<table border="1" style="width: 300px">
    <tr>
        <th>用户ID</th>
        <th>用户姓名</th>
    </tr>
    <tr th:each="user:${list}">
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
    </tr>
</table>

<br>
<br>
<hr>
<span shiro:authenticated>已登录<br/></span>
<span shiro:hasRole="role1" >role1</span>
<span shiro:hasRole="role2" >role2</span>
<span shiro:hasRole="role3" >role3</span>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值