com.kingen.shiro.realm.ShiroDbRealm.java Source code

Java tutorial

Introduction

Here is the source code for com.kingen.shiro.realm.ShiroDbRealm.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.kingen.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
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.authc.credential.HashedCredentialsMatcher;
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.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.kingen.bean.Menu;
import com.kingen.bean.User;
import com.kingen.service.account.AccountService;
import com.kingen.shiro.credentials.RetryLimitHashedCredentialsMatcher;
import com.kingen.util.Encodes;

/**
 * shiro realm
 * @author wj
 *
 */
public class ShiroDbRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

    @Autowired
    protected AccountService accountService;

    /**
     * ?,.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        logger.info("doGetAuthenticationInfo----");

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = null;
        try {
            user = accountService.findUserByLoginName(token.getUsername());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (user != null) {

            byte[] salt = Encodes.decodeHex(user.getSalt());//16
            //user ?principal
            return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(salt), getName());

            //         return new SimpleAuthenticationInfo();
        } else {
            return null;
        }
    }

    /**
     * PasswordHash.
     */
    //XML?
    /*
    @PostConstruct
    public void initCredentialsMatcher() {
    //      RetryLimitHashedCredentialsMatcher  matcher = new RetryLimitHashedCredentialsMatcher(AccountService.HASH_ALGORITHM);
       HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(AccountService.HASH_ALGORITHM);
       matcher.setHashIterations(AccountService.HASH_INTERATIONS);
       setCredentialsMatcher(matcher);
           
    }
    */

    /**
     * ?, ???.
     * controller@RequeirePermissions? AuthorizationInfo ??????info????
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("doGetAuthorizationInfo----");

        User user = (User) principals.getPrimaryPrincipal();
        //Authorization ????????????
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        try {
            Set<String> roles = new HashSet<String>();
            //?employee?finance?hr?boss..??????
            // ?adminuser???
            roles.add("admin".equals(user.getUserId()) ? "admin" : "user");

            List<Menu> menus = accountService.findMenuByuserId(user.getUserId());
            Set<String> resources = new HashSet<String>();
            for (Menu m : menus) {
                if (!StringUtils.isEmpty(m.getFunId())) { //???? NULL?????
                    resources.add(m.getFunId());
                }
            }

            authorizationInfo.setRoles(roles);
            authorizationInfo.setStringPermissions(resources);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("realm ?");
        }
        return authorizationInfo;

    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}