前边项目鉴权一向接纳的Shiro,那是在Spring
MVC里面使用的可比多,而且都以用XML来配置,用Shiro来做权限调整相对比较轻便而且成熟,而且自个儿直接都把Shiro的session放在mongodb中,那些相比较吻合mongodb的宏图初衷,而且在分布式项目中mongodb也当作2其中间层,用来很好很有益解决分布式环境下的session同步的难题。

 

 自从SpringBoot出版之后笔者的品种还不错SpringBoot的就会用SpringBoot,用MAVEN做统1集中管理也很有益于,即使SpringBoot也提供了壹套权限安全框架Spring
Security,然则绝对来讲仍然不是太好用,所以还是用Shiro来的有益一点,SpringBoot集成Shiro要比Spring
MVC要轻易的多,至少未有一批XML布署,看起来更舒心,那么接下去我们就起来集成。

 第3步必然是在MAVEN中先加多Shiro和mongo的信赖,作者用的Shiro版本是

<shiro.version>1.2.3</shiro.version>

增多凭借:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>${shiro.version}</version>
</dependency>

<dependency>
    <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.0.0</version>
</dependency>
  <dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-mongodb</artifactId>
  <version>1.7.0.RELEASE</version>
</dependency>

然后在application.xml或yml中配置mongodb

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=SHIRO_INFO

配置达成现在大家开端专业写Shiro认证的代码,先自定义八个鉴权realm,继承自AuthorizingRealm

public class ShiroDbRealm extends AuthorizingRealm {

  /**
   * 用户信息操作
   */
  private SystemUserService systemUserService;

  public ShiroDbRealm() {}

  public ShiroDbRealm(SystemUserService systemUserService) {
    this.systemUserService = systemUserService;
  }

  /**
   * 授权信息
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo info = (SimpleAuthorizationInfo) ShiroKit.getShiroSessionAttr("perms");
    if (null != info && !CollectionUtils.isEmpty(info.getRoles())
        && !CollectionUtils.isEmpty(info.getStringPermissions())) {
      return info;

    }
    return null;

  }

  /**
   * 认证信息
   */
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
      throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    String userName = token.getUsername();
    if (userName != null && !"".equals(userName)) {
      SystemUser key = new SystemUser();
      key.setLoginName(token.getUsername());
      key.setPassword(String.valueOf(token.getPassword()));
      SystemUser user = systemUserService.login(key);

      if (user != null) {
        Subject userTemp = SecurityUtils.getSubject();
        userTemp.getSession().setAttribute("userId", user.getId());
        userTemp.getSession().setAttribute("userName", user.getUserName());
        return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(), getName());
      }
    }
    return null;
  }

}

存储session进mongodb的Repository和实现:

public interface ShiroSessionRepository {

  /**
   * 
   * @param session
   */
  void saveSession(Session session);
  ......
}

MongoDBSessionRepository.java

public class MongoDBSessionRepository implements ShiroSessionRepository {
    private MongoTemplate mongoTemplate;

    public MongoDBSessionRepository() {}

    public MongoDBSessionRepository(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    @Override
    public void saveSession(Session session) {
      if (session == null || session.getId() == null) {
        return;
      }
      SessionBean bean = new SessionBean();
      bean.setKey(getSessionKey(session.getId()));
      bean.setValue(SerializeUtil.serialize(session));
      bean.setPrincipal(null);
      bean.setHost(session.getHost());
      bean.setStartTimestamp(session.getStartTimestamp());
      bean.setLastAccessTime(session.getLastAccessTime());
      bean.setTimeoutTime(getTimeoutTime(session.getStartTimestamp(), session.getTimeout()));
      mongoTemplate.insert(bean);
    }
    ......
}

ShiroSessionDAO.java

public class ShiroSessionDAO extends AbstractSessionDAO {

 /**
  * 日志记录器
  */
 private static final Logger log = LoggerFactory.getLogger(ShiroSessionDAO.class);

 /**
  * 数据库存储
  */
 private ShiroSessionRepository shiroSessionRepository;

 /**
  * 
  * @return
  */
 public ShiroSessionRepository getShiroSessionRepository() {
   return shiroSessionRepository;
 }

 /**
  * 
  * @param shiroSessionRepository
  */
 public void setShiroSessionRepository(ShiroSessionRepository shiroSessionRepository) {
   this.shiroSessionRepository = shiroSessionRepository;
 }

 @Override
 public void update(Session session) throws UnknownSessionException {
   getShiroSessionRepository().updateSession(session);
 }

 @Override
 public void delete(Session session) {
   if (session == null) {
     log.error("session can not be null,delete failed");
     return;
   }
   Serializable id = session.getId();
   if (id != null) {
     getShiroSessionRepository().deleteSession(id);
   }
 }

 @Override
 public Collection<Session> getActiveSessions() {
   return getShiroSessionRepository().getAllSessions();
 }

 @Override
 protected Serializable doCreate(Session session) {
   Serializable sessionId = this.generateSessionId(session);
   this.assignSessionId(session, sessionId);
   getShiroSessionRepository().saveSession(session);
   return sessionId;
 }

 @Override
 protected Session doReadSession(Serializable sessionId) {
   return getShiroSessionRepository().getSession(sessionId);
 }

}

OK!全体基础类已经成功,最后写三个config用来任何开头化和配置Shiro

@Configuration
public class ShiroConfig {
  @Resource
  private MongoTemplate mongoTemplate;
  @Resource
  private SystemUserService systemUserService;// 这是用来判断用户名和密码的service

  @Bean
  public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

    shiroFilterFactoryBean.setSecurityManager(securityManager);
    shiroFilterFactoryBean.setLoginUrl("/login");
    shiroFilterFactoryBean.setSuccessUrl("/index");
    shiroFilterFactoryBean.setUnauthorizedUrl("/403");

    // 拦截器.
    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
    filterChainDefinitionMap.put("/static/**", "anon");
    filterChainDefinitionMap.put("/ajaxLogin", "anon");
    filterChainDefinitionMap.put("/libs/**", "anon");
    filterChainDefinitionMap.put("**", "anon");
    filterChainDefinitionMap.put("/logout", "logout");
    filterChainDefinitionMap.put("/**", "authc");

    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilterFactoryBean;
  }

  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
      DefaultWebSecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor adv = new AuthorizationAttributeSourceAdvisor();
    adv.setSecurityManager(securityManager);
    return adv;
  }

  @Bean
  public DefaultWebSecurityManager securityManager(DefaultWebSessionManager sessionManager,
      ShiroDbRealm myShiroRealm) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    // 设置realm.
    securityManager.setRealm(myShiroRealm);
    securityManager.setSessionManager(sessionManager);
    return securityManager;
  }

  /**
   * 身份认证realm; (这里传递systemUserService给自定义的ShiroDbRealm初始化)
   * 
   * @return
   */
  @Bean
  public ShiroDbRealm myShiroRealm() {
    ShiroDbRealm myShiroRealm = new ShiroDbRealm(systemUserService);
    return myShiroRealm;
  }

  @Bean
  public DefaultWebSessionManager sessionManager(ShiroSessionDAO shiroSessionDao) {
    DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    sessionManager.setGlobalSessionTimeout(1800000l);
    sessionManager.setDeleteInvalidSessions(true);
    sessionManager.setSessionValidationSchedulerEnabled(true);
    sessionManager.setSessionDAO(shiroSessionDao);
    sessionManager.setSessionIdCookieEnabled(true);
    SimpleCookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(1800000);
    sessionManager.setSessionIdCookie(cookie);
    return sessionManager;
  }

  @Bean
  public ShiroSessionDAO shiroSessionDao(MongoDBSessionRepository shiroSessionRepository) {
    ShiroSessionDAO dao = new ShiroSessionDAO();
    dao.setShiroSessionRepository(shiroSessionRepository);
    return dao;
  }

  @Bean
  MongoDBSessionRepository shiroSessionRepository() {
    MongoDBSessionRepository resp = new MongoDBSessionRepository(mongoTemplate);
    return resp;
  }


}

好了,马到功成,那里只是四个轻便易行的布局,代码也是本身从类别里面节选和改变过的,至于在controller里面怎么利用,怎么办分歧权限的鉴权工作那就在友好的代码里面达成就行。

 

小说来源:

dhttp://www.tianshangkun.com/2017/11/10/SpringBoot%E9%9B%86%E6%88%90Shiro%E5%B9%B6%E7%94%A8MongoDB%E5%81%9ASession%E5%AD%98%E5%82%A8/

越多参考情节:http://www.roncoo.com/article/index?tn=SpringBoot

相关文章

网站地图xml地图