⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 authorizationmanager.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     *            for, which must be non-null. If null, the result of this     *            method always returns <code>false</code>     * @return <code>true</code> if the Subject supplied with the WikiContext     *         posesses the Role, GroupPrincipal or desired     *         user Principal, <code>false</code> otherwise     */    protected boolean hasRoleOrPrincipal( WikiSession session, Principal principal )    {        // If either parameter is null, always deny        if( session == null || principal == null )        {            return false;        }        // If principal is role, delegate to isUserInRole        if( AuthenticationManager.isRolePrincipal( principal ) )        {            return isUserInRole( session, principal );        }        // We must be looking for a user principal, assuming that the user        // has been properly logged in.        // So just look for a name match.        if( session.isAuthenticated() && AuthenticationManager.isUserPrincipal( principal ) )        {            String principalName = principal.getName();            Principal[] userPrincipals = session.getPrincipals();            for( Principal userPrincipal : userPrincipals )            {                if( userPrincipal.getName().equals( principalName ) )                {                    return true;                }            }        }        return false;    }    /**     * Initializes AuthorizationManager with an engine and set of properties.     * Expects to find property 'jspwiki.authorizer' with a valid Authorizer     * implementation name to take care of role lookup operations.     * @param engine the wiki engine     * @param properties the set of properties used to initialize the wiki engine     * @throws WikiException if the AuthorizationManager cannot be initialized     */    @SuppressWarnings("deprecation")    public final void initialize( WikiEngine engine, Properties properties ) throws WikiException    {        m_engine = engine;        m_useJAAS = AuthenticationManager.SECURITY_JAAS.equals( properties.getProperty(AuthenticationManager.PROP_SECURITY, AuthenticationManager.SECURITY_JAAS ) );        if( !m_useJAAS ) return;        //        //  JAAS authorization continues        //        m_authorizer = getAuthorizerImplementation( properties );        m_authorizer.initialize( engine, properties );        // Initialize local security policy        try        {            String policyFileName = properties.getProperty( POLICY, DEFAULT_POLICY );            URL policyURL = AuthenticationManager.findConfigFile( engine, policyFileName );                        if (policyURL != null)             {                File policyFile = new File( policyURL.getPath() );                m_localPolicy = new LocalPolicy( policyFile, engine.getContentEncoding() );                m_localPolicy.refresh();                log.info( "Initialized default security policy: " + policyFile.getAbsolutePath() );            }            else            {                StringBuffer sb = new StringBuffer( "JSPWiki was unable to initialize the " );                sb.append( "default security policy (WEB-INF/jspwiki.policy) file. " );                sb.append( "Please ensure that the jspwiki.policy file exists in the default location. " );                sb.append( "This file should exist regardless of the existance of a global policy file. " );                sb.append( "The global policy file is identified by the java.security.policy variable. " );                WikiSecurityException wse = new WikiSecurityException( sb.toString() );                log.fatal( sb.toString(), wse );                throw wse;            }        }        catch ( PolicyException e )        {            log.error("Could not initialize local security policy: " + e.getMessage() );            throw new WikiException( e.getMessage() );        }    }    /**     * Returns <code>true</code> if JSPWiki's JAAS authorization system     * is used for authorization in addition to container controls.     * @return the result     */    protected boolean isJAASAuthorized()    {        return m_useJAAS;    }    /**     * Attempts to locate and initialize a Authorizer to use with this manager.     * Throws a WikiException if no entry is found, or if one fails to     * initialize.     * @param props jspwiki.properties, containing a     *            'jspwiki.authorization.provider' class name     * @return a Authorizer used to get page authorization information     * @throws WikiException     */    private final Authorizer getAuthorizerImplementation( Properties props ) throws WikiException    {        String authClassName = props.getProperty( PROP_AUTHORIZER, DEFAULT_AUTHORIZER );        return (Authorizer) locateImplementation( authClassName );    }    private final Object locateImplementation( String clazz ) throws WikiException    {        if ( clazz != null )        {            try            {                Class<?> authClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.authorize", clazz );                Object impl = authClass.newInstance();                return impl;            }            catch( ClassNotFoundException e )            {                log.fatal( "Authorizer " + clazz + " cannot be found", e );                throw new WikiException( "Authorizer " + clazz + " cannot be found" );            }            catch( InstantiationException e )            {                log.fatal( "Authorizer " + clazz + " cannot be created", e );                throw new WikiException( "Authorizer " + clazz + " cannot be created" );            }            catch( IllegalAccessException e )            {                log.fatal( "You are not allowed to access this authorizer class", e );                throw new WikiException( "You are not allowed to access this authorizer class" );            }        }        throw new NoRequiredPropertyException( "Unable to find a " + PROP_AUTHORIZER + " entry in the properties.",                                               PROP_AUTHORIZER );    }    /**     * Checks to see if the local security policy allows a particular static Permission.     * Do not use this method for normal permission checks; use     * {@link #checkPermission(WikiSession, Permission)} instead.     * @param principals the Principals to check     * @param permission the Permission     * @return the result     */    protected boolean allowedByLocalPolicy( Principal[] principals, Permission permission )    {        for ( Principal principal : principals )        {            // Get ProtectionDomain for this Principal from cache, or create new one            ProtectionDomain pd = m_cachedPds.get( principal );            if ( pd == null )            {                ClassLoader cl = this.getClass().getClassLoader();                CodeSource cs = new CodeSource( null, (Certificate[])null );                pd = new ProtectionDomain( cs, null, cl, new Principal[]{ principal } );                m_cachedPds.put( principal, pd );            }            // Consult the local policy and get the answer            if ( m_localPolicy.implies( pd, permission ) )            {                return true;            }        }        return false;    }    /**     * Determines whether a Subject possesses a given "static" Permission as     * defined in the security policy file. This method uses standard Java 2     * security calls to do its work. Note that the current access control     * context's <code>codeBase</code> is effectively <em>this class</em>,     * not that of the caller. Therefore, this method will work best when what     * matters in the policy is <em>who</em> makes the permission check, not     * what the caller's code source is. Internally, this method works by     * executing <code>Subject.doAsPrivileged</code> with a privileged action     * that simply calls {@link java.security.AccessController#checkPermission(Permission)}.     * @see AccessController#checkPermission(java.security.Permission) . A     *       caught exception (or lack thereof) determines whether the privilege     *       is absent (or present).     * @param session the WikiSession whose permission status is being queried     * @param permission the Permission the Subject must possess     * @return <code>true</code> if the Subject posesses the permission,     *         <code>false</code> otherwise     */    protected final boolean checkStaticPermission( final WikiSession session, final Permission permission )    {        if( !m_useJAAS ) return true;        Boolean allowed = (Boolean) WikiSession.doPrivileged( session, new PrivilegedAction<Boolean>()        {            public Boolean run()            {                try                {                    // Check the JVM-wide security policy first                    AccessController.checkPermission( permission );                    return Boolean.TRUE;                }                catch( AccessControlException e )                {                    // Global policy denied the permission                }                // Try the local policy - check each Role/Group and User Principal                if ( allowedByLocalPolicy( session.getRoles(), permission ) ||                     allowedByLocalPolicy( session.getPrincipals(), permission ) )                {                    return Boolean.TRUE;                }                return Boolean.FALSE;            }        } );        return allowed.booleanValue();    }    /**     * <p>Given a supplied string representing a Principal's name from an Acl, this     * method resolves the correct type of Principal (role, group, or user).     * This method is guaranteed to always return a Principal.     * The algorithm is straightforward:</p>     * <ol>     * <li>If the name matches one of the built-in {@link com.ecyrd.jspwiki.auth.authorize.Role} names,     * return that built-in Role</li>     * <li>If the name matches one supplied by the current     * {@link com.ecyrd.jspwiki.auth.Authorizer}, return that Role</li>     * <li>If the name matches a group managed by the     * current {@link com.ecyrd.jspwiki.auth.authorize.GroupManager}, return that Group</li>     * <li>Otherwise, assume that the name represents a user     * principal. Using the current {@link com.ecyrd.jspwiki.auth.user.UserDatabase}, find the     * first user who matches the supplied name by calling     * {@link com.ecyrd.jspwiki.auth.user.UserDatabase#find(String)}.</li>     * <li>Finally, if a user cannot be found, manufacture     * and return a generic {@link com.ecyrd.jspwiki.auth.acl.UnresolvedPrincipal}</li>     * </ol>     * @param name the name of the Principal to resolve     * @return the fully-resolved Principal     */    public final Principal resolvePrincipal( String name )    {        if( !m_useJAAS )        {            return new UnresolvedPrincipal(name);        }        // Check built-in Roles first        Role role = new Role(name);        if ( Role.isBuiltInRole( role ) )        {            return role;        }        // Check Authorizer Roles        Principal principal = m_authorizer.findRole( name );        if ( principal != null )        {            return principal;        }        // Check Groups        principal = m_engine.getGroupManager().findRole( name );        if ( principal != null )        {            return principal;        }        // Ok, no luck---this must be a user principal        Principal[] principals = null;        UserProfile profile = null;        UserDatabase db = m_engine.getUserManager().getUserDatabase();        try        {            profile = db.find( name );            principals = db.getPrincipals( profile.getLoginName() );            for (int i = 0; i < principals.length; i++)            {                principal = principals[i];                if ( principal.getName().equals( name ) )                {                    return principal;                }            }        }        catch( NoSuchPrincipalException e )        {            // We couldn't find the user...        }        // Ok, no luck---mark this as unresolved and move on        return new UnresolvedPrincipal( name );    }    // events processing .......................................................    /**     * Registers a WikiEventListener with this instance.     * @param listener the event listener     */    public final synchronized void addWikiEventListener( WikiEventListener listener )    {        WikiEventManager.addWikiEventListener( this, listener );    }    /**     * Un-registers a WikiEventListener with this instance.     * @param listener the event listener     */    public final synchronized void removeWikiEventListener( WikiEventListener listener )    {        WikiEventManager.removeWikiEventListener( this, listener );    }    /**     *  Fires a WikiSecurityEvent of the provided type, user,     *  and permission to all registered listeners.     *     * @see com.ecyrd.jspwiki.event.WikiSecurityEvent     * @param type        the event type to be fired     * @param user        the user associated with the event     * @param permission  the permission the subject must possess     */    protected final void fireEvent( int type, Principal user, Object permission )    {        if ( WikiEventManager.isListening(this) )        {            WikiEventManager.fireEvent(this,new WikiSecurityEvent(this,type,user,permission));        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -