spring boot 集成 shiro

版本说明:

spring boot : 1.5.8.RELEASE

shiro: 1.4.0

在没有shiro-spring-boot-web-stater之前,我们通常的做法是把xx-shiro.xml中bean在configuration中定义,或者就是xml中进行定义。

当看了shiro源码后,在spring boot 中来使用已经非常简单方便了,

以下做一个简单说明备忘。


1、依赖(以maven工程为例)

在pom.xml的依赖配置中增加:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.4.0</version>
</dependency>

2、自定义 Realm,重写认证、授权方法就好

这个想必你一定清楚,为了与我们自己的系统框架的认证、授权相结合,根据实际情况来实现就好。

以下是自己的一个实现例子,可以参考:

package cn.test.itobc.web.shiro;

import org.apache.shiro.authc.*;
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.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by csdn小徕虫 on 2017/11/15.
 */
public class LawOfficeRealm extends AuthorizingRealm {

    @Autowired
    private TransientUserService transientUserService;
    /**
     * 重写授权信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        AuthUser authUser = (AuthUser) principals.getPrimaryPrincipal();

        if (authUser != null && !StringUtils.isEmpty(authUser.getAccount())) {
            // 查询用户授权信息
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 查询用户角色信息 info.addRole(xx);
            // 查询用户权限信息 info.addStringPermission(xx);
            List<String> dbRoles = transientUserService.queryUserRoles(authUser.getAccount());
            if(dbRoles != null)
            {
                for(String role : dbRoles)
                {
                    info.addRole(role);
                }
            }

            return info;
        }
        return null;
    }

    /**
     * 重写认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 通过表单接收的用户名
        String userAccount = token.getPrincipal().toString();
        if (StringUtils.isEmpty(userAccount)) {
            throw new UnknownAccountException();
        }
        // 通过userService查询库中的用户
        AuthUser dbUser = transientUserService.queryUserByAccount(userAccount);
        // 如果查询库中后,用户信息对时,根据需要相应的抛出 UnknownAccountException IncorrectCredentialsException
        if(dbUser == null)
        {
            throw new UnknownAccountException();
        }
        if(!dbUser.getPasswd().equals(String.valueOf(token.getPassword())))
        {
            throw new IncorrectCredentialsException();
        }

        List<Object> principals = CollectionUtils.asList(dbUser, userAccount);
        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());

        return new SimpleAuthenticationInfo(principalCollection, token.getPassword());
    }
}
 
3、定义shiro的配置类
package cn.test.itobc.web.shiro;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by csdn小徕虫 on 2017/11/15.
 */
@Configuration
public class ShiroConfig {

    @Bean
    public Realm realm() {
	LawOfficeRealm lawOfficeRealm = new LawOfficeRealm();
lawOfficeRealm.setCachingEnabled(true); return lawOfficeRealm; } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); chainDefinition.addPathDefinition("/views/login.html", "anon");//page chainDefinition.addPathDefinition("/login", "anon");//service chainDefinition.addPathDefinition("/logout", "anon");//service chainDefinition.addPathDefinition("/**", "authc"); // 这里配置很灵活,细节看官方文档或源码。根据自己的需求来过滤就可以了。
	// 针对自己的业务不同,不同的的路径匹配,采用不同的过滤器

        return chainDefinition;
    }

    @Bean
    protected CacheManager cacheManager(){
        return new MemoryConstrainedCacheManager();
    }


}

4、配置文件

采用的是yml格式进行配置,如果是properties的话,相应的加点就好了。

shiro:
  loginUrl: /views/login.html
  unauthorizedUrl: /a/unauthorized
  userNativeSessionManager: true
  sessionManager:
    sessionIdUrlRewritingEnabled: false

5、如果有更细粒度或是更深的应用,只能自己参考官方文档了。

6、参考文档:

这几个链接地址,是经自己看了网上各种说明描述之后,整理筛选留下来的。我觉得相比较来说是比较好的url了。

http://www.jianshu.com/p/dbe441dcdbcf

http://www.baeldung.com/apache-shiro

https://dzone.com/articles/protecting-a-spring-boot-app-with-apache-shiro

https://shiro.apache.org/spring-boot.html

http://shiro.apache.org/caching.html


7、Git地址:

https://github.com/apache/shiro.git


没事就多上GitHub,祝君好运!

-- Love is share.


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值