SpringBoot整合Shiro

SpringBoot整合shiro

加入shiro的jar包

   <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.3.2</version>
    </dependency>

编写shiro配置文件类

@Configuration
public class ShiroConfig {
/**
  配置认证管理器
*/
@Bean
public WebSecurityManager securityManager(){
DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
    webSecurityManager.setRealm(new MyRealm());
    return  webSecurityManager;
}
 /**
  配置shiroFilter
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(){
    ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
    shiroFilter.setSecurityManager(securityManager());
    shiroFilter.setLoginUrl("/toLogin");
    shiroFilter.setSuccessUrl("/index"); 
    shiroFilter.setUnauthorizedUrl("/sorry");//这个不知道为什么没有跳转,后面写一个全局异常处理
    Map<String, String> filterChainDefinitionMap = new HashMap<>();
    filterChainDefinitionMap.put("/login","anon");
    filterChainDefinitionMap.put("/index","authc");
    filterChainDefinitionMap.put("/*","authc");
    shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilter;

}
/**
    配置使用权限注解
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
    DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
    advisorAutoProxyCreator.setProxyTargetClass(true);
    return advisorAutoProxyCreator;
}

/**
  启用Aop
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
    return authorizationAttributeSourceAdvisor;
}
/**
  整合thymeleaf页面权限需要加入的
*/
@Bean
public ShiroDialect shiroDialect() {
    return new ShiroDialect();
}

编写自定义realm类

public class MyRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
    System.out.println("username:"+usernamePasswordToken.getUsername());
    System.out.println("password:"+usernamePasswordToken.getCredentials());
    User user=null;
    if(usernamePasswordToken.getUsername().equals("zhangsan")){
      user =  new User("zhangsan","zhangsan");
    }
    if(usernamePasswordToken.getUsername().equals("admin")){
        user = new User("admin","admin");
    }

    AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
    return  authenticationInfo;
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
    String  username = (String) principals.getPrimaryPrincipal();
    Set<String>  permissions =null;
 if("admin".equals(username)){
     permissions= new HashSet<>();
     permissions.add("resource1:get");
     permissions.add("resource2:get");

 }
 if("zhangsan".equals(username)){
     permissions= new HashSet<>();
     permissions.add("resource1:get");
 }

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
     simpleAuthorizationInfo.addStringPermissions(permissions);
 return  simpleAuthorizationInfo;

  }
}

编写Controller

@Controller
public class UserController {
    @RequestMapping("/toLogin")
    public String toLogin(){
        System.out.println("to login~~~~~~~~~");
        return "login";
    }
    @RequestMapping(value = "/login",method =RequestMethod.POST)
    public String login(User user,Map<String,Object> map){
        System.out.println(user);
        if(user.getUsername()==null||"".equals(user.getUsername())){
            return "login";
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new              UsernamePasswordToken(user.getUsername(),user.getPassword());
         try {
             subject.login(usernamePasswordToken);
         }catch (IncorrectCredentialsException e){
             System.err.println("密码不对哦");
             map.put("error","密码错误");
             return "login";
         }

         System.out.println("login 成功");
         map.put("user",user);
        return "index";
    }
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @RequestMapping("/logout")
    public String loginOut(){
        Subject subject = SecurityUtils.getSubject();
        System.out.println("用户注销登陆");
        subject.logout();
        return "login";
    }

    @RequiresPermissions("resource1:get")
    @RequestMapping("/resource1")
    public String  resource1(){
        System.out.println("resource1");
        return "resource1";
    }
    @RequiresPermissions("resource2:get")
    @RequestMapping("/resource2")
    public String  resource2(){
        System.out.println("resource2");
        return "resource2";
    }
    @RequestMapping("/sorry")
    public  String sorry(){
        System.out.println("sorry");
        return "sorry";
    }

}

编写捕捉权限异常类

@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(AuthorizationException.class)
    public String  unauthorizedException(Exception e, HttpServletRequest request){
        request.setAttribute("javax.servlet.error.status_code",403);
        return "forward:error";
    }
}

shiro整合thymeleaf

1、加入jar包

<dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
 </dependency>

2、修改shiro的配置文件,添加

@Bean
public ShiroDialect shiroDialect() {
    return new ShiroDialect();
}  
//上面已经加入

3、html引入如下代码:

<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

4、标签的使用

<span shiro:hasPermission="resource1:get">
  <a href="/resource1">resource1</a>
</span>
<span shiro:hasPermission="resource2:get">
    <a href="/resource2">resource2</a>
</span>
posted @ 2019-09-06 16:11  BingoJ  阅读(193)  评论(0编辑  收藏  举报