spring boot 整合shiro 前后端分离+权限不足异常捕获

 

1.引入pom

         	
        
            org.apache.shiro
            shiro-spring
            1.4.0
        
		
            org.apache.shiro
            shiro-ehcache
            1.4.0
          
             
                org.apache.shiro
                shiro-core
             
          
        
        
        
          org.springframework
          spring-aspects
          5.0.7.RELEASE
         

2.MyShiroRealm://name:数据库中的  pwd:数据库中的MD5  getName():realm name

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
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.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
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;

import com.guo.vo.User;

public class MyShiroRealm extends AuthorizingRealm {
		    //角色权限和对应权限添加
		    @Override
		    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		        //获取登录用户名
		        String name = (String) principalCollection.getPrimaryPrincipal();
		        //添加角色和权限
		        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

		        //添加角色
		        simpleAuthorizationInfo.addRole("admin2");

		        //添加权限
		       simpleAuthorizationInfo.addStringPermission("create");
		       simpleAuthorizationInfo.addStringPermission("detail");
		        return simpleAuthorizationInfo;
		    }

		    //用户认证
		    @Override
		    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken atoken) throws AuthenticationException {

		        UsernamePasswordToken token = (UsernamePasswordToken) atoken;

		        String name = token.getUsername();

		        if (name == null) {
		            return null;
		        }//这里验证authenticationToken和simpleAuthenticationInfo的信息
		        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, "123456", getName());
		        return simpleAuthenticationInfo;

		    }
}
 //这里验证authenticationToken和simpleAuthenticationInfo的信息
		        //name:数据库中的  pwd:数据库中的MD5  getName():realm name
		        User user=new User();
		        user.setName(name);
		        List list = userService.findBySelective(user);
		        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(list.get(0).getName(), list.get(0).getPassWord(), getName());
		        return simpleAuthenticationInfo;

从数据库中查询

3.ShiroConfiguration

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class ShiroConfiguration {
    //将自己的验证方式加入容器
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        return myShiroRealm;
    }

    //权限管理,配置主要是Realm的管理认证
    @Bean
    public org.apache.shiro.mgt.SecurityManager securityManager(CacheManager cacheManager, SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager);
        securityManager.setRealm(myShiroRealm());
        securityManager.setCacheManager(cacheManager);
        return securityManager;
    }

    //Filter工厂,设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(org.apache.shiro.mgt.SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map map = new HashMap();
        //注意过滤器配置顺序 不能颠倒
        //游客,开发权限
        map.put("/guest/**", "anon");
        //用户,需要角色权限 “user”
        map.put("/user/**", "roles[user]");
        //管理员,需要角色权限 “admin”
        map.put("/admin/**", "roles[admin]");
        //开放登陆接口
        map.put("/doLogin", "anon");
        map.put("/logout","logout");
        //放行静态页面
        map.put("/static/**", "anon");
        //其余接口一律拦截
        //主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截
        map.put("/**", "authc");
        //登录:登录失败后跳转的页面或跳转的接口地址
        shiroFilterFactoryBean.setLoginUrl("/login");
        //首页:登录成功后跳转的页面或跳转的接口地址
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //错误页面,认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

   //加入注解的使用,不加入这个注解不生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(org.apache.shiro.mgt.SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    @Bean
    public CacheManager cacheManager(){
        return new EhCacheManager();
    }


    @Bean
    public SessionDAO sessionDAO(){
        return new EnterpriseCacheSessionDAO();
    }

    @Bean
    public SessionManager sessionManager(SessionDAO sessionDAO){
        DefaultWebSessionManager manager = new DefaultWebSessionManager();
        manager.setSessionDAO(sessionDAO);
        manager.setGlobalSessionTimeout(3600000);
        manager.setSessionValidationInterval(3600000);
        return manager;
    }
}

4.LoginController

import javax.security.auth.Subject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
	    //登录拦截返回
	    @GetMapping("/login")
	    public String login(){
	        return "need login";
	    }

	    //登录
	    @GetMapping("/doLogin")
	    public String doLogin(String uid, String pwd){
	        //添加用户认证信息
	        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
	        UsernamePasswordToken token = new UsernamePasswordToken(uid,pwd);
	        try{
	            //进行验证,这里可以捕获异常,然后返回对应信息
	            subject.login(token);
	        }
	        catch(Exception e){
	            return "login failed";
	        }

	        return "login success";
	    }
	    //登录成功返回
	    @RequestMapping(value = "/index")
	    public String index(){
	        return "index";
	    }

	    //登出
	    @RequestMapping(value = "/logout")
	    public String logout(){
	        return "logout";
	    }

	    //错误页面展示
	    @GetMapping("/error")
	    public String error(){
	        return "error ok!";
	    }

	   
	    @RequiresRoles(value={"admin","user"},logical = Logical.OR)
	    @RequestMapping(value = "/create")
	    public String create(){
	        return "Create success!";
	    }
	    
	   
	    @RequiresPermissions("detail")
	    @RequestMapping(value = "/detail")
	    public String detail(){
	        return "uid";
	    }
}

5.全局异常捕获

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;




/**
 * 1、新建一个Class,这里取名为GlobalDefaultExceptionHandler
 * 2、在class上添加注解,@ControllerAdvice;
 * 3、在class中添加一个方法
 * 4、在方法上添加@ExcetionHandler拦截相应的异常信息;
 * 5、如果返回的是View -- 方法的返回值是ModelAndView;
 * 6、如果返回的是String或者是Json数据,那么需要在方法上添加@ResponseBody注解.
 * 
 * 
 * @author gc
 * @version v.0.1
 * @date 2018年8月18日
 */
    @ControllerAdvice
    public class GlobalDefaultExceptionHandler {



       @ExceptionHandler(UnauthorizedException.class)
       @ResponseBody
       public String defaultExceptionHandler(HttpServletRequest req,Exception e){


         return "对不起,你没有访问权限!";
       }
    }

 

你可能感兴趣的:(spring,boot)