pinked

导航

shiro

shiro

依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.5.1</version>
</dependency>

<!--log4j及相关-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>2.0.0-alpha1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>2.0.0-alpha1</version>
</dependency>

log4j配置

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

quickstart

//获得当前用户对象
Subject currentUser = SecurityUtils.getSubject();
//获得当前用户session
Session session = currentUser.getSession();
//判断当前用户是否认证
currentUser.isAuthenticated()
//获得当前用户的认证
currentUser.getPrincipal()
//判断当前用户是否拥有角色
currentUser.hasRole("schwartz")
//获得当前用户的权限
currentUser.isPermitted("lightsaber:wield")
//注销
currentUser.logout();

与springboot整合

依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.5.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

自定义UserRealm并重写方法

public class UserRealm extends AuthorizingRealm{}

ShiroConfig

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean:3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager getDefaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(getDefaultWebSecurityManager);
        return bean;
    }

    //DefaultWebSecurityMannger:2
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //自定义realm类:1
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

拦截实现

ShiroConfig

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager getDefaultWebSecurityManager) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    //设置安全管理器
    bean.setSecurityManager(getDefaultWebSecurityManager);

    LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
    //添加权限
    filterMap.put("/user/*", "authc");
    bean.setFilterChainDefinitionMap(filterMap);
    //跳转登录页
    bean.setLoginUrl("/toLogin");
    return bean;
}

过滤器

anon: 无需认证即可访问
authc: 需要认证才可访问
user: 点击“记住我”功能可访问
perms: 拥有权限才可以访问
role: 拥有某个角色权限才能访问

用户认证

controller

@RequestMapping("/login")
public String login(String username, String password, Model model){
    //获得当前用户
    Subject subject = SecurityUtils.getSubject();
    //封装用户的登录数据
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try{
        //执行登录的方法
        subject.login(token);
        return "index";
    }catch (UnknownAccountException e){
        model.addAttribute("msg", "用户不存在");
        return "login";
    }catch (IncorrectCredentialsException e){
        model.addAttribute("msg", "密码错误");
        return "login";
    }
}

UserRealm

//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken userToken = (UsernamePasswordToken) token;
    //调用service获得数据库中的用户
    User user = userService.queryUserByName(userToken.getUsername());
    if (user==null){
        //抛出异常 UnknownAccountException
        return null;
    }
    //把用户存放在session中
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    session.setAttribute("loginUser", user);
    //密码认证由shiro完成
    return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}

添加权限

ShiroConfig

//添加权限
filterMap.put("/user/add", "perms[user:add]");
filterMap.put("/user/update", "perms[user:update]");
//无权限则跳转至
bean.setUnauthorizedUrl("/unauth");

UserRealm

//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //拿到当前登录的对象
    Subject subject = SecurityUtils.getSubject();
    //拿到user对象
    User currentUser = (User) subject.getPrincipal();
    //从数据库中获得用户的权限
    info.addStringPermission(currentUser.getPerms());
    return info;
}

与thymeleaf整合

依赖

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

ShiroConfig

//整合shiroDialect:thymeleaf-shiro
@Bean
public ShiroDialect getShiroDialect(){
    return new ShiroDialect();
}

controller

@RequestMapping("/logout")
public String logout(){
    Subject subject = SecurityUtils.getSubject();
    subject.logout();
    return "redirect:/";
}

index.html

根据权限展示

<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">添加</a></div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">更新</a>
</div>
<div th:switch="${session.loginUser==null}">
    <a th:case="true" th:href="@{/toLogin}">登录</a>
    <a th:case="false" th:href="@{/logout}">注销</a>
</div>

posted on 2020-02-27 21:51  pinked  阅读(170)  评论(0编辑  收藏  举报