net.cloudkit.enterprises.infrastructure.shiro.ShiroDbRealm.java Source code

Java tutorial

Introduction

Here is the source code for net.cloudkit.enterprises.infrastructure.shiro.ShiroDbRealm.java

Source

/*
 * Copyright (C) 2015 The CloudKit Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.cloudkit.enterprises.infrastructure.shiro;

import com.google.common.base.Objects;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ShiroDbRealm.java
 * PrincipalsSubject??Subject???????????????Subject?Principals?--???
 * ?
 * shiro??Shiro??--Subject??????ID
 * ?Credentials?Subject???????????X.509?
 * ?/???????????????????
 * Authenticating
 * Subject??
 * 1.Subject???
 * 2.?Authenticating???
 * 3.???????
 *
 * @author hongquanli <hongquanli@qq.com>
 * @version 1.0 20131030 ?11:46:30
 */
public class ShiroDbRealm extends AuthorizingRealm {

    //    private static final String ALGORITHM = "MD5";

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

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;

    //    @Resource
    //    private AuthenticationService authenticationService;

    /**
     * ?
     * ???(?, ).
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {

        //UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        //logger.info("??Subject?token" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
        //
        //// ???
        //String username = token.getUsername();
        //if (username != null && !"".equals(username)) {
        //    // AuthenticationService authenticationService = ApplicationServiceFactroy.authenticationService();
        //    // ???
        //    // AuthUserDTO authUser = memberService.getAuthUser(username);
        //    if (authUser != null) {
        //
        //        if (authUser.isDisabled()) {
        //            throw new DisabledAccountException();
        //        }
        //        // ?(SALT)
        //        byte[] salt = EncodeHelper.decodeHex(authUser.getSalt());
        //        // ???
        //        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(new ShiroUser(authUser.getLoginName(), null), authUser.getPassword(), ByteSource.Util.bytes(salt), getName());
        //
        //        // this.setSession("user", user);
        //        return authcInfo;
        //    } else {
        //        // NoFoundAccountException
        //        throw new UnknownAccountException();
        //    }
        //}
        return null;
    }

    /**
     * ?
     * ???(?, ???).
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName());
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();

        // AuthenticationService authenticationService = ApplicationServiceFactroy.authenticationService();
        // ???
        // AuthUserDTO authUser = authenticationService.getAuthUser(shiroUser.loginName);
        // User user = authenticationService.findUserByLoginName(shiroUser.loginName);

        List<String> roleList = new ArrayList<String>();
        List<String> permissionList = new ArrayList<String>();

        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();

        // TODO ????
        /*
        for (Role role : user.getRoles()) {
        // Role???
        // info.addRole(role.getName());
        roleList.add(role.getCode());
        Set<Permission> permissions = role.getPermissions();
        for (Permission permission : permissions) {
            // Permission???
            // simpleAuthorInfo.addStringPermission(permission.getCode());
            permissionList.add(permission.getCode());
        }
        }
        */

        // XXX  ,???,?user
        simpleAuthorInfo.addRole("user");
        // ??
        simpleAuthorInfo.addStringPermission("user:manage");

        simpleAuthorInfo.addRoles(roleList);
        simpleAuthorInfo.addStringPermissions(permissionList);

        return simpleAuthorInfo;

        // ????,(String)principals.fromRealm(this.getName()).iterator().next();
        // String currentUsername = (String)super.getAvailablePrincipal(principals);

        // String username = (String) principals.fromRealm(getName()).iterator().next();
        // if (username != null) {
        //     // ??
        //     Collection<String> pers = businessManager.queryPermissions(username);
        //     if (pers != null && !pers.isEmpty()) {
        //         SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //         for (String each : pers)
        //             simpleAuthorInfo.addStringPermissions(each);
        //
        //         return simpleAuthorInfo;
        //     }
        // }
        // return null;

        // ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName()).iterator().next();
        // User user = UserService.findUserByLoginName(shiroUser.getLoginName());
        // // Permission???
        // if (user != null) {
        //     SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //     for (Role role : user.getRoles()) {
        //         for (Permission permission : role.getPermisssions()) {
        //             info.addStringPermission(permission.getValue());
        //         }
        //     }
        //     return simpleAuthorInfo;
        // } else {
        //     return null;
        // }
    }

    /**
     * PasswordHash.
     */
    @PostConstruct
    public void initCredentialsMatcher() {

        // // MD5
        // HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);
        // setCredentialsMatcher(matcher);

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(HASH_ALGORITHM);
        matcher.setHashIterations(HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }

    /**
     * ?ShiroSession,
     * Controller,HttpSession.getAttribute(key)??
     */
    @SuppressWarnings("unused")
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            logger.info("Session[" + session.getTimeout() + "]");
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

    /**
     * ??.
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * ??.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }

    /**
     * Authentication,Subject??????.
     */
    public static class ShiroUser implements Serializable {

        private static final long serialVersionUID = 423613100213753942L;

        /** ?? */
        public String loginName;

        public String name;

        public Map<String, Object> otherDataMap;

        public ShiroUser(String loginName, String name) {
            this.loginName = loginName;
            this.name = name;
        }

        public ShiroUser(String loginName, String name, Map<String, Object> otherDataMap) {
            this.loginName = loginName;
            this.name = name;
            this.otherDataMap = otherDataMap;
        }

        public String getName() {
            return name;
        }

        public String getLoginName() {
            return loginName;
        }

        public Map<String, Object> getOtherDataMap() {
            return otherDataMap;
        }

        /**
         * <shiro:principal />.
         */
        @Override
        public String toString() {
            return loginName;
        }

        /**
         * ?hashCode,?loginName;
         */
        @Override
        public int hashCode() {
            return Objects.hashCode(loginName);
        }

        /**
         * ?equals,?loginName;
         */
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ShiroUser other = (ShiroUser) obj;
            if (loginName == null) {
                if (other.loginName != null)
                    return false;
            } else if (!loginName.equals(other.loginName))
                return false;
            return true;
        }
    }
}