springboot集成shiro

第一步. pom依赖


		
			org.apache.shiro
			shiro-spring
			1.4.0
		
		
			org.apache.shiro
			shiro-core
			1.3.2
		
		
			org.apache.shiro
			shiro-web
			1.3.2
		

第二步:创建实体
springboot集成shiro_第1张图片

package com.servingcloud.xszcloud.web.shiro.entity;

import lombok.Data;

import java.util.List;

/**
 * Created by 
 * on 2018/10/9
 */
@Data
public class User {
    private int id;
    private String username;
    private String password;

    //用户的角色   一对多关系
    private List roleList;
}

package com.servingcloud.xszcloud.web.shiro.entity;

import lombok.Data;

import java.util.List;

/**
 * Created by 
 * on 2018/10/9
 */
@Data
public class Role {
    private int id;
    private String rolename;//角色名称
    private String roledesc;//角色描述

    private List permissions;//角色权限关系  多对多  一个角色对应多个权限

}

package com.servingcloud.xszcloud.web.shiro.entity;

import lombok.Data;

import java.util.List;

/**
 * Created by 
 * on 2018/10/9
 */
@Data
public class Permission {
    private int id;
    private String modelname;
    private String permission;

    private List roles;//角色权限关系   多对多
}

第三步:MyShiroRelam extends AuthorizingRealm 并写ShiroConfig类

package com.servingcloud.xszcloud.web.shiro.config;

import com.servingcloud.xszcloud.web.shiro.entity.Permission;
import com.servingcloud.xszcloud.web.shiro.entity.Role;
import com.servingcloud.xszcloud.web.shiro.entity.User;
import com.servingcloud.xszcloud.web.shiro.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.springframework.beans.factory.annotation.Autowired;

/**
 * Created by 
 * on 2018/10/9
 */
public class MyShiroRelam extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户权限配置。。。。。。。。。。");
        //访问@RequirePermission注解的url时触发
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userInfo  = (User)principals.getPrimaryPrincipal();
        //获得用户的角色,及权限进行绑定
        for(Role role:userInfo.getRoleList()){
            authorizationInfo.addRole(role.getRolename());
            for(Permission p:role.getPermissions()){
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }

    //验证用户登录信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("验证用户登录信息");
        String username = (String)token.getPrincipal();
        System.out.println("登录用户名: "+username);
        System.out.println(token.getCredentials());
        //从数据库查询出User信息及用户关联的角色,权限信息,以备权限分配时使用
        User user = userService.findUserByName(username);
        if(null == user) return null;
        System.out.println("username: "+user.getUsername()+" ; password : "+user.getPassword());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getPassword(), //密码
                getName()  //realm name
        );
        return authenticationInfo;
    }
}

package com.servingcloud.xszcloud.web.shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
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 org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;


@Configuration
public class ShiroConfig {

    public ShiroConfig(){
        System.out.println("ShiroConfig  init ....");
    }

    /**
     shiro过滤器配置
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(DefaultWebSecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器.
        Map filterChainDefinitionMap = new LinkedHashMap();
        //权限配置
        //filterChainDefinitionMap.put("/stu/addStu","perms[student:aaaa]");
        // 配置不会被拦截的链接 顺序判断  相关静态资源
        filterChainDefinitionMap.put("/assets/**", "anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/font/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/products/**", "anon");
        filterChainDefinitionMap.put("/Widget/**", "anon");
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/swagger-resources", "anon");
        filterChainDefinitionMap.put("/swagger-resources/configuration/security", "anon");
        filterChainDefinitionMap.put("/swagger-resources/configuration/ui", "anon");
        filterChainDefinitionMap.put("/v2/api-docs", "anon");
        filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");

        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");

        //:这是一个坑呢,一不小心代码就不好使了;

        //
        filterChainDefinitionMap.put("/**", "authc");
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");

        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
    /*
    加密方式配置
    */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
        return hashedCredentialsMatcher;
    }

    /*
    认证器配置
    */
    @Bean
    public MyShiroRelam myShiroRealm(){
        MyShiroRelam myShiroRelam = new MyShiroRelam();
        //myShiroRelam.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRelam;
    }

    /*
    安全管理器配置
    */
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    /*
    开启@RequirePermission注解的配置,要结合DefaultAdvisorAutoProxyCreator一起使用,或者导入aop的依赖
    */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /* @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
          DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
          advisorAutoProxyCreator.setProxyTargetClass(true);
          return advisorAutoProxyCreator;
    }*/


    /*
    定义Spring MVC的异常处理器
    */
    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
        mappings.setProperty("UnauthorizedException","403");//处理shiro的认证未通过异常
        r.setExceptionMappings(mappings);  // None by default
        r.setDefaultErrorView("error");    // No default
        r.setExceptionAttribute("ex");     // Default is "exception"
        return r;
    }
}

第四步:dao层

package com.servingcloud.xszcloud.web.shiro.mapper;

import com.servingcloud.xszcloud.web.shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * Created by 
 * on 2018/10/9
 */
@Repository
@Mapper
public interface IUserDao {
    public User findUserByName(String name);

}

***********************************************************************************************
UserDao.xml文件的编写
 





    
    
    
    
        
        
        
        
            
            
            
        
    




第五步:service和impl

package com.servingcloud.xszcloud.web.shiro.service;

import com.servingcloud.xszcloud.web.shiro.entity.User;

/**
 * Created by 
 * on 2018/10/9
 */
public interface IUserService {
    public User findUserByName(String name);
}

package com.servingcloud.xszcloud.web.shiro.service.impl;

import com.servingcloud.xszcloud.web.shiro.mapper.IUserDao;
import com.servingcloud.xszcloud.web.shiro.entity.User;
import com.servingcloud.xszcloud.web.shiro.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 
 * on 2018/10/9
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;

    @Override
    public User findUserByName(String name) {
        return userDao.findUserByName(name);
    }

}

第六步:controller

package com.servingcloud.xszcloud.web.shiro.controller;

import com.servingcloud.xszcloud.web.shiro.service.IUserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by 
 * on 2018/10/9
 */
@RestController
public class HomeController {
    @Autowired
    private IUserService userService;

    @RequestMapping({"/","/index"})
    public String root(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map map){
        System.out.println("user login .....");
        String exception = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("exception=" + exception);
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在:");
                msg = "unknownAccount";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                msg = "incorrectPassword";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> "+exception;
                System.out.println("else -- >" + exception);
            }
        }
        map.put("msg", msg);
        //认证成功由shiro框架自行处理
        return "login";
    }


    //访问此连接时会触发MyShiroRealm中的权限分配方法
    @RequestMapping("/permission")
    @RequiresPermissions("student:test")
    public void test(){
        System.out.println("permission  test");
    }
}

第七步:创建权限表

create table user(
 id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
 username VARCHAR(20) NOT NULL ,
 password VARCHAR(20) not null
);

create table role(
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
rolename VARCHAR(20) NOT NULL,
roledesc VARCHAR(20)
);


create table permission(
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
modelname VARCHAR(20) NOT NULL ,
permission VARCHAR(20) NOT NULL
);

create table user_role(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
uid int NOT NULL ,
rid int NOT NULL
);


create table role_permission(
id INT NOT NULL  PRIMARY KEY  AUTO_INCREMENT,
rid int NOT NULL ,
pid int NOT NULL
);


最后一步:验证…

你可能感兴趣的:(java,springboot,shiro)