You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shiro.apache.org by ad...@apache.org on 2010/05/26 20:34:49 UTC
svn commit: r948527 [33/38] - in /incubator/shiro:
branches/shiro-root-1.0.x/ branches/shiro-root-1.0.x/all/
branches/shiro-root-1.0.x/core/src/main/java/org/apache/shiro/
branches/shiro-root-1.0.x/core/src/main/java/org/apache/shiro/aop/
branches/shir...
Modified: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java?rev=948527&r1=948526&r2=948527&view=diff
==============================================================================
--- incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java (original)
+++ incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java Wed May 26 18:34:28 2010
@@ -1,190 +1,190 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.shiro.web.config;
-
-import org.apache.shiro.config.Ini;
-import org.apache.shiro.config.IniFactorySupport;
-import org.apache.shiro.config.IniSecurityManagerFactory;
-import org.apache.shiro.config.ReflectionBuilder;
-import org.apache.shiro.util.CollectionUtils;
-import org.apache.shiro.util.Factory;
-import org.apache.shiro.web.filter.mgt.FilterChainManager;
-import org.apache.shiro.web.filter.mgt.FilterChainResolver;
-import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterConfig;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * A {@link Factory} that creates {@link FilterChainResolver} instances based on {@link Ini} configuration.
- *
- * @author The Apache Shiro Project (shiro-dev@incubator.apache.org)
- * @since 1.0
- */
-public class IniFilterChainResolverFactory extends IniFactorySupport<FilterChainResolver> {
-
- public static final String FILTERS = "filters";
- public static final String URLS = "urls";
-
- private static transient final Logger log = LoggerFactory.getLogger(IniFilterChainResolverFactory.class);
-
- private FilterConfig filterConfig;
-
- private Map<String, ?> defaultBeans;
-
- public IniFilterChainResolverFactory() {
- super();
- }
-
- public IniFilterChainResolverFactory(Ini ini) {
- super(ini);
- }
-
- public IniFilterChainResolverFactory(Ini ini, Map<String, ?> defaultBeans) {
- this(ini);
- this.defaultBeans = defaultBeans;
- }
-
- public FilterConfig getFilterConfig() {
- return filterConfig;
- }
-
- public void setFilterConfig(FilterConfig filterConfig) {
- this.filterConfig = filterConfig;
- }
-
- protected FilterChainResolver createInstance(Ini ini) {
- FilterChainResolver filterChainResolver = createDefaultInstance();
- if (filterChainResolver instanceof PathMatchingFilterChainResolver) {
- PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) filterChainResolver;
- FilterChainManager manager = resolver.getFilterChainManager();
- buildChains(manager, ini);
- }
- return filterChainResolver;
- }
-
- protected FilterChainResolver createDefaultInstance() {
- FilterConfig filterConfig = getFilterConfig();
- if (filterConfig != null) {
- return new PathMatchingFilterChainResolver(filterConfig);
- } else {
- return new PathMatchingFilterChainResolver();
- }
- }
-
- protected void buildChains(FilterChainManager manager, Ini ini) {
- //filters section:
- Ini.Section section = ini.getSection(FILTERS);
-
- if (!CollectionUtils.isEmpty(section)) {
- String msg = "The [{}] section has been deprecated and will be removed in a future release! Please " +
- "move all object configuration (filters and all other objects) to the [{}] section.";
- log.warn(msg, FILTERS, IniSecurityManagerFactory.MAIN_SECTION_NAME);
- }
-
- Map<String, Object> defaults = new LinkedHashMap<String, Object>();
-
- Map<String, Filter> defaultFilters = manager.getFilters();
-
- //now let's see if there are any object defaults in addition to the filters
- //these can be used to configure the filters:
- //create a Map of objects to use as the defaults:
- if (!CollectionUtils.isEmpty(defaultFilters)) {
- defaults.putAll(defaultFilters);
- }
- //User-provided objects must come _after_ the default filters - to allow the user-provided
- //ones to override the default filters if necessary.
- if (!CollectionUtils.isEmpty(this.defaultBeans)) {
- defaults.putAll(this.defaultBeans);
- }
-
- Map<String, Filter> filters = getFilters(section, defaults);
-
- //add the filters to the manager:
- registerFilters(filters, manager);
-
- //urls section:
- section = ini.getSection(URLS);
- createChains(section, manager);
- }
-
- protected void registerFilters(Map<String, Filter> filters, FilterChainManager manager) {
- if (!CollectionUtils.isEmpty(filters)) {
- boolean init = getFilterConfig() != null; //only call filter.init if there is a FilterConfig available
- for (Map.Entry<String, Filter> entry : filters.entrySet()) {
- String name = entry.getKey();
- Filter filter = entry.getValue();
- manager.addFilter(name, filter, init);
- }
- }
- }
-
- protected Map<String, Filter> getFilters(Map<String, String> section, Map<String, ?> defaults) {
-
- Map<String, Filter> filters;
-
- if (!CollectionUtils.isEmpty(section)) {
- ReflectionBuilder builder = new ReflectionBuilder(defaults);
- Map<String, ?> built = builder.buildObjects(section);
- filters = extractFilters(built);
- } else {
- filters = extractFilters(defaults);
- }
-
- return filters;
- }
-
- private Map<String, Filter> extractFilters(Map<String, ?> objects) {
- if (CollectionUtils.isEmpty(objects)) {
- return null;
- }
- Map<String, Filter> filterMap = new LinkedHashMap<String, Filter>();
- for (Map.Entry<String, ?> entry : objects.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof Filter) {
- filterMap.put(key, (Filter) value);
- }
- }
- return filterMap;
- }
-
- protected void createChains(Map<String, String> urls, FilterChainManager manager) {
- if (CollectionUtils.isEmpty(urls)) {
- if (log.isDebugEnabled()) {
- log.debug("No urls to process.");
- }
- return;
- }
-
- if (log.isTraceEnabled()) {
- log.trace("Before url processing.");
- }
-
- for (Map.Entry<String, String> entry : urls.entrySet()) {
- String path = entry.getKey();
- String value = entry.getValue();
- manager.createChain(path, value);
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.shiro.web.config;
+
+import org.apache.shiro.config.Ini;
+import org.apache.shiro.config.IniFactorySupport;
+import org.apache.shiro.config.IniSecurityManagerFactory;
+import org.apache.shiro.config.ReflectionBuilder;
+import org.apache.shiro.util.CollectionUtils;
+import org.apache.shiro.util.Factory;
+import org.apache.shiro.web.filter.mgt.FilterChainManager;
+import org.apache.shiro.web.filter.mgt.FilterChainResolver;
+import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterConfig;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A {@link Factory} that creates {@link FilterChainResolver} instances based on {@link Ini} configuration.
+ *
+ * @author The Apache Shiro Project (shiro-dev@incubator.apache.org)
+ * @since 1.0
+ */
+public class IniFilterChainResolverFactory extends IniFactorySupport<FilterChainResolver> {
+
+ public static final String FILTERS = "filters";
+ public static final String URLS = "urls";
+
+ private static transient final Logger log = LoggerFactory.getLogger(IniFilterChainResolverFactory.class);
+
+ private FilterConfig filterConfig;
+
+ private Map<String, ?> defaultBeans;
+
+ public IniFilterChainResolverFactory() {
+ super();
+ }
+
+ public IniFilterChainResolverFactory(Ini ini) {
+ super(ini);
+ }
+
+ public IniFilterChainResolverFactory(Ini ini, Map<String, ?> defaultBeans) {
+ this(ini);
+ this.defaultBeans = defaultBeans;
+ }
+
+ public FilterConfig getFilterConfig() {
+ return filterConfig;
+ }
+
+ public void setFilterConfig(FilterConfig filterConfig) {
+ this.filterConfig = filterConfig;
+ }
+
+ protected FilterChainResolver createInstance(Ini ini) {
+ FilterChainResolver filterChainResolver = createDefaultInstance();
+ if (filterChainResolver instanceof PathMatchingFilterChainResolver) {
+ PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) filterChainResolver;
+ FilterChainManager manager = resolver.getFilterChainManager();
+ buildChains(manager, ini);
+ }
+ return filterChainResolver;
+ }
+
+ protected FilterChainResolver createDefaultInstance() {
+ FilterConfig filterConfig = getFilterConfig();
+ if (filterConfig != null) {
+ return new PathMatchingFilterChainResolver(filterConfig);
+ } else {
+ return new PathMatchingFilterChainResolver();
+ }
+ }
+
+ protected void buildChains(FilterChainManager manager, Ini ini) {
+ //filters section:
+ Ini.Section section = ini.getSection(FILTERS);
+
+ if (!CollectionUtils.isEmpty(section)) {
+ String msg = "The [{}] section has been deprecated and will be removed in a future release! Please " +
+ "move all object configuration (filters and all other objects) to the [{}] section.";
+ log.warn(msg, FILTERS, IniSecurityManagerFactory.MAIN_SECTION_NAME);
+ }
+
+ Map<String, Object> defaults = new LinkedHashMap<String, Object>();
+
+ Map<String, Filter> defaultFilters = manager.getFilters();
+
+ //now let's see if there are any object defaults in addition to the filters
+ //these can be used to configure the filters:
+ //create a Map of objects to use as the defaults:
+ if (!CollectionUtils.isEmpty(defaultFilters)) {
+ defaults.putAll(defaultFilters);
+ }
+ //User-provided objects must come _after_ the default filters - to allow the user-provided
+ //ones to override the default filters if necessary.
+ if (!CollectionUtils.isEmpty(this.defaultBeans)) {
+ defaults.putAll(this.defaultBeans);
+ }
+
+ Map<String, Filter> filters = getFilters(section, defaults);
+
+ //add the filters to the manager:
+ registerFilters(filters, manager);
+
+ //urls section:
+ section = ini.getSection(URLS);
+ createChains(section, manager);
+ }
+
+ protected void registerFilters(Map<String, Filter> filters, FilterChainManager manager) {
+ if (!CollectionUtils.isEmpty(filters)) {
+ boolean init = getFilterConfig() != null; //only call filter.init if there is a FilterConfig available
+ for (Map.Entry<String, Filter> entry : filters.entrySet()) {
+ String name = entry.getKey();
+ Filter filter = entry.getValue();
+ manager.addFilter(name, filter, init);
+ }
+ }
+ }
+
+ protected Map<String, Filter> getFilters(Map<String, String> section, Map<String, ?> defaults) {
+
+ Map<String, Filter> filters;
+
+ if (!CollectionUtils.isEmpty(section)) {
+ ReflectionBuilder builder = new ReflectionBuilder(defaults);
+ Map<String, ?> built = builder.buildObjects(section);
+ filters = extractFilters(built);
+ } else {
+ filters = extractFilters(defaults);
+ }
+
+ return filters;
+ }
+
+ private Map<String, Filter> extractFilters(Map<String, ?> objects) {
+ if (CollectionUtils.isEmpty(objects)) {
+ return null;
+ }
+ Map<String, Filter> filterMap = new LinkedHashMap<String, Filter>();
+ for (Map.Entry<String, ?> entry : objects.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof Filter) {
+ filterMap.put(key, (Filter) value);
+ }
+ }
+ return filterMap;
+ }
+
+ protected void createChains(Map<String, String> urls, FilterChainManager manager) {
+ if (CollectionUtils.isEmpty(urls)) {
+ if (log.isDebugEnabled()) {
+ log.debug("No urls to process.");
+ }
+ return;
+ }
+
+ if (log.isTraceEnabled()) {
+ log.trace("Before url processing.");
+ }
+
+ for (Map.Entry<String, String> entry : urls.entrySet()) {
+ String path = entry.getKey();
+ String value = entry.getValue();
+ manager.createChain(path, value);
+ }
+ }
+}
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/WebIniSecurityManagerFactory.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/WebIniSecurityManagerFactory.java?rev=948527&r1=948526&r2=948527&view=diff
==============================================================================
--- incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/WebIniSecurityManagerFactory.java (original)
+++ incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/WebIniSecurityManagerFactory.java Wed May 26 18:34:28 2010
@@ -1,78 +1,78 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.shiro.web.config;
-
-import org.apache.shiro.config.Ini;
-import org.apache.shiro.config.IniSecurityManagerFactory;
-import org.apache.shiro.mgt.SecurityManager;
-import org.apache.shiro.web.filter.mgt.DefaultFilter;
-import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
-
-import javax.servlet.Filter;
-import java.util.Map;
-
-/**
- * Differs from the parent class only in the {@link #createDefaultInstance()} method, to
- * ensure a web-capable {@code SecurityManager} instance is created by default.
- *
- * @author The Apache Shiro Project (shiro-dev@incubator.apache.org)
- * @since 1.0
- */
-public class WebIniSecurityManagerFactory extends IniSecurityManagerFactory {
-
- /**
- * Creates a new {@code WebIniSecurityManagerFactory} instance which will construct web-capable
- * {@code SecurityManager} instances.
- */
- public WebIniSecurityManagerFactory() {
- super();
- }
-
- /**
- * Creates a new {@code WebIniSecurityManagerFactory} instance which will construct web-capable
- * {@code SecurityManager} instances. Uses the given {@link Ini} instance to construct the instance.
- *
- * @param config the Ini configuration that will be used to construct new web-capable {@code SecurityManager}
- * instances.
- */
- public WebIniSecurityManagerFactory(Ini config) {
- super(config);
- }
-
- /**
- * Simply returns <code>new {@link DefaultWebSecurityManager}();</code> to ensure a web-capable
- * {@code SecurityManager} is available by default.
- *
- * @return a new web-capable {@code SecurityManager} instance.
- */
- @Override
- protected SecurityManager createDefaultInstance() {
- return new DefaultWebSecurityManager();
- }
-
- @SuppressWarnings({"unchecked"})
- @Override
- protected Map<String, ?> createDefaults(Ini ini, Ini.Section mainSection) {
- Map defaults = super.createDefaults(ini, mainSection);
- //add the default filters:
- Map<String, Filter> defaultFilters = DefaultFilter.createInstanceMap(null);
- defaults.putAll(defaultFilters);
- return defaults;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.shiro.web.config;
+
+import org.apache.shiro.config.Ini;
+import org.apache.shiro.config.IniSecurityManagerFactory;
+import org.apache.shiro.mgt.SecurityManager;
+import org.apache.shiro.web.filter.mgt.DefaultFilter;
+import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
+
+import javax.servlet.Filter;
+import java.util.Map;
+
+/**
+ * Differs from the parent class only in the {@link #createDefaultInstance()} method, to
+ * ensure a web-capable {@code SecurityManager} instance is created by default.
+ *
+ * @author The Apache Shiro Project (shiro-dev@incubator.apache.org)
+ * @since 1.0
+ */
+public class WebIniSecurityManagerFactory extends IniSecurityManagerFactory {
+
+ /**
+ * Creates a new {@code WebIniSecurityManagerFactory} instance which will construct web-capable
+ * {@code SecurityManager} instances.
+ */
+ public WebIniSecurityManagerFactory() {
+ super();
+ }
+
+ /**
+ * Creates a new {@code WebIniSecurityManagerFactory} instance which will construct web-capable
+ * {@code SecurityManager} instances. Uses the given {@link Ini} instance to construct the instance.
+ *
+ * @param config the Ini configuration that will be used to construct new web-capable {@code SecurityManager}
+ * instances.
+ */
+ public WebIniSecurityManagerFactory(Ini config) {
+ super(config);
+ }
+
+ /**
+ * Simply returns <code>new {@link DefaultWebSecurityManager}();</code> to ensure a web-capable
+ * {@code SecurityManager} is available by default.
+ *
+ * @return a new web-capable {@code SecurityManager} instance.
+ */
+ @Override
+ protected SecurityManager createDefaultInstance() {
+ return new DefaultWebSecurityManager();
+ }
+
+ @SuppressWarnings({"unchecked"})
+ @Override
+ protected Map<String, ?> createDefaults(Ini ini, Ini.Section mainSection) {
+ Map defaults = super.createDefaults(ini, mainSection);
+ //add the default filters:
+ Map<String, Filter> defaultFilters = DefaultFilter.createInstanceMap(null);
+ defaults.putAll(defaultFilters);
+ return defaults;
+ }
+}
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/WebIniSecurityManagerFactory.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/config/package-info.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/AccessControlFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/PathConfigProcessor.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AnonymousFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticatingFilter.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticatingFilter.java?rev=948527&r1=948526&r2=948527&view=diff
==============================================================================
--- incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticatingFilter.java (original)
+++ incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticatingFilter.java Wed May 26 18:34:28 2010
@@ -1,108 +1,108 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.shiro.web.filter.authc;
-
-import org.apache.shiro.authc.AuthenticationException;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.authc.UsernamePasswordToken;
-import org.apache.shiro.subject.Subject;
-
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-/**
- * An <code>AuthenticationFilter</code> that is capable of automatically performing an authentication attempt
- * based on the incoming request.
- *
- * @author Les Hazlewood
- * @since 0.9
- */
-public abstract class AuthenticatingFilter extends AuthenticationFilter {
-
- //TODO - complete JavaDoc
-
- protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
- AuthenticationToken token = createToken(request, response);
- if (token == null) {
- String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
- "must be created in order to execute a login attempt.";
- throw new IllegalStateException(msg);
- }
- try {
- Subject subject = getSubject(request, response);
- subject.login(token);
- return onLoginSuccess(token, subject, request, response);
- } catch (AuthenticationException e) {
- return onLoginFailure(token, e, request, response);
- }
- }
-
- protected abstract AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception;
-
- protected AuthenticationToken createToken(String username, String password,
- ServletRequest request, ServletResponse response) {
- boolean rememberMe = isRememberMe(request);
- String host = getHost(request);
- return createToken(username, password, rememberMe, host);
- }
-
- protected AuthenticationToken createToken(String username, String password,
- boolean rememberMe, String host) {
- return new UsernamePasswordToken(username, password, rememberMe, host);
- }
-
- protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
- ServletRequest request, ServletResponse response) throws Exception {
- return true;
- }
-
- protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
- ServletRequest request, ServletResponse response) {
- return false;
- }
-
- /**
- * Returns the host name or IP associated with the current subject. This method is primarily provided for use
- * during construction of an <code>AuthenticationToken</code>.
- * <p/>
- * The default implementation merely returns {@link ServletRequest#getRemoteHost()}.
- *
- * @param request the incoming ServletRequest
- * @return the <code>InetAddress</code> to associate with the login attempt.
- */
- protected String getHost(ServletRequest request) {
- return request.getRemoteHost();
- }
-
- /**
- * Returns <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
- * current <code>request</code>, <code>false</code> otherwise.
- * <p/>
- * This implementation always returns <code>false</code> and is provided as a template hook to subclasses that
- * support <code>rememberMe</code> logins and wish to determine <code>rememberMe</code> in a custom mannner
- * based on the current <code>request</code>.
- *
- * @param request the incoming ServletRequest
- * @return <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
- * current <code>request</code>, <code>false</code> otherwise.
- */
- protected boolean isRememberMe(ServletRequest request) {
- return false;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.shiro.web.filter.authc;
+
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.subject.Subject;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * An <code>AuthenticationFilter</code> that is capable of automatically performing an authentication attempt
+ * based on the incoming request.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthenticatingFilter extends AuthenticationFilter {
+
+ //TODO - complete JavaDoc
+
+ protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
+ AuthenticationToken token = createToken(request, response);
+ if (token == null) {
+ String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
+ "must be created in order to execute a login attempt.";
+ throw new IllegalStateException(msg);
+ }
+ try {
+ Subject subject = getSubject(request, response);
+ subject.login(token);
+ return onLoginSuccess(token, subject, request, response);
+ } catch (AuthenticationException e) {
+ return onLoginFailure(token, e, request, response);
+ }
+ }
+
+ protected abstract AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception;
+
+ protected AuthenticationToken createToken(String username, String password,
+ ServletRequest request, ServletResponse response) {
+ boolean rememberMe = isRememberMe(request);
+ String host = getHost(request);
+ return createToken(username, password, rememberMe, host);
+ }
+
+ protected AuthenticationToken createToken(String username, String password,
+ boolean rememberMe, String host) {
+ return new UsernamePasswordToken(username, password, rememberMe, host);
+ }
+
+ protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
+ ServletRequest request, ServletResponse response) throws Exception {
+ return true;
+ }
+
+ protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
+ ServletRequest request, ServletResponse response) {
+ return false;
+ }
+
+ /**
+ * Returns the host name or IP associated with the current subject. This method is primarily provided for use
+ * during construction of an <code>AuthenticationToken</code>.
+ * <p/>
+ * The default implementation merely returns {@link ServletRequest#getRemoteHost()}.
+ *
+ * @param request the incoming ServletRequest
+ * @return the <code>InetAddress</code> to associate with the login attempt.
+ */
+ protected String getHost(ServletRequest request) {
+ return request.getRemoteHost();
+ }
+
+ /**
+ * Returns <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
+ * current <code>request</code>, <code>false</code> otherwise.
+ * <p/>
+ * This implementation always returns <code>false</code> and is provided as a template hook to subclasses that
+ * support <code>rememberMe</code> logins and wish to determine <code>rememberMe</code> in a custom mannner
+ * based on the current <code>request</code>.
+ *
+ * @param request the incoming ServletRequest
+ * @return <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
+ * current <code>request</code>, <code>false</code> otherwise.
+ */
+ protected boolean isRememberMe(ServletRequest request) {
+ return false;
+ }
+}
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticatingFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/AuthenticationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/BasicHttpAuthenticationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/PassThruAuthenticationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/UserFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authc/package-info.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/AuthorizationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HostFilter.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HostFilter.java?rev=948527&r1=948526&r2=948527&view=diff
==============================================================================
--- incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HostFilter.java (original)
+++ incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HostFilter.java Wed May 26 18:34:28 2010
@@ -1,106 +1,106 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.shiro.web.filter.authz;
-
-import org.apache.shiro.util.StringUtils;
-
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import java.util.regex.Pattern;
-import java.util.Map;
-
-/**
- * A Filter that can allow or deny access based on the host that sent the request.
- *
- * <b>WARNING:</b> NOT YET FULLY IMPLEMENTED!!! Work in progress.
- *
- * @since 1.0
- */
-public class HostFilter extends AuthorizationFilter {
-
- public static final String IPV4_QUAD_REGEX = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2(?:[0-4][0-9]|5[0-5]))";
-
- public static final String IPV4_REGEX = "(?:" + IPV4_QUAD_REGEX + "\\.){3}" + IPV4_QUAD_REGEX + "$";
- public static final Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
-
- public static final String PRIVATE_CLASS_B_SUBSET = "(?:1[6-9]|2[0-9]|3[0-1])";
-
- public static final String PRIVATE_CLASS_A_REGEX = "10\\.(?:" + IPV4_QUAD_REGEX + "\\.){2}" + IPV4_QUAD_REGEX + "$";
-
- public static final String PRIVATE_CLASS_B_REGEX =
- "172\\." + PRIVATE_CLASS_B_SUBSET + "\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
-
- public static final String PRIVATE_CLASS_C_REGEX = "192\\.168\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
-
- Map<String, String> authorizedIps; //user-configured IP (which can be wildcarded) to constructed regex mapping
- Map<String, String> deniedIps;
- Map<String, String> authorizedHostnames;
- Map<String, String> deniedHostnames;
-
-
- public void setAuthorizedHosts(String authorizedHosts) {
- if (!StringUtils.hasText(authorizedHosts)) {
- throw new IllegalArgumentException("authorizedHosts argument cannot be null or empty.");
- }
- String[] hosts = StringUtils.tokenizeToStringArray(authorizedHosts, ", \t");
-
- for (String host : hosts) {
- //replace any periods with \\. to ensure the regex works:
- String periodsReplaced = host.replace(".", "\\.");
- //check for IPv4:
- String wildcardsReplaced = periodsReplaced.replace("*", IPV4_QUAD_REGEX);
-
- if (IPV4_PATTERN.matcher(wildcardsReplaced).matches()) {
- authorizedIps.put(host, wildcardsReplaced);
- } else {
-
- }
-
-
- }
-
- }
-
- public void setDeniedHosts(String deniedHosts) {
- if (!StringUtils.hasText(deniedHosts)) {
- throw new IllegalArgumentException("deniedHosts argument cannot be null or empty.");
- }
- }
-
- protected boolean isIpv4Candidate(String host) {
- String[] quads = StringUtils.tokenizeToStringArray(host, ".");
- if (quads == null || quads.length != 4) {
- return false;
- }
- for (String quad : quads) {
- if (!quad.equals("*")) {
- try {
- Integer.parseInt(quad);
- } catch (NumberFormatException nfe) {
- return false;
- }
- }
- }
- return true;
- }
-
- protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
- throw new UnsupportedOperationException("Not yet fully implemented!!!" );
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.shiro.web.filter.authz;
+
+import org.apache.shiro.util.StringUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.util.regex.Pattern;
+import java.util.Map;
+
+/**
+ * A Filter that can allow or deny access based on the host that sent the request.
+ *
+ * <b>WARNING:</b> NOT YET FULLY IMPLEMENTED!!! Work in progress.
+ *
+ * @since 1.0
+ */
+public class HostFilter extends AuthorizationFilter {
+
+ public static final String IPV4_QUAD_REGEX = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2(?:[0-4][0-9]|5[0-5]))";
+
+ public static final String IPV4_REGEX = "(?:" + IPV4_QUAD_REGEX + "\\.){3}" + IPV4_QUAD_REGEX + "$";
+ public static final Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
+
+ public static final String PRIVATE_CLASS_B_SUBSET = "(?:1[6-9]|2[0-9]|3[0-1])";
+
+ public static final String PRIVATE_CLASS_A_REGEX = "10\\.(?:" + IPV4_QUAD_REGEX + "\\.){2}" + IPV4_QUAD_REGEX + "$";
+
+ public static final String PRIVATE_CLASS_B_REGEX =
+ "172\\." + PRIVATE_CLASS_B_SUBSET + "\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
+
+ public static final String PRIVATE_CLASS_C_REGEX = "192\\.168\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
+
+ Map<String, String> authorizedIps; //user-configured IP (which can be wildcarded) to constructed regex mapping
+ Map<String, String> deniedIps;
+ Map<String, String> authorizedHostnames;
+ Map<String, String> deniedHostnames;
+
+
+ public void setAuthorizedHosts(String authorizedHosts) {
+ if (!StringUtils.hasText(authorizedHosts)) {
+ throw new IllegalArgumentException("authorizedHosts argument cannot be null or empty.");
+ }
+ String[] hosts = StringUtils.tokenizeToStringArray(authorizedHosts, ", \t");
+
+ for (String host : hosts) {
+ //replace any periods with \\. to ensure the regex works:
+ String periodsReplaced = host.replace(".", "\\.");
+ //check for IPv4:
+ String wildcardsReplaced = periodsReplaced.replace("*", IPV4_QUAD_REGEX);
+
+ if (IPV4_PATTERN.matcher(wildcardsReplaced).matches()) {
+ authorizedIps.put(host, wildcardsReplaced);
+ } else {
+
+ }
+
+
+ }
+
+ }
+
+ public void setDeniedHosts(String deniedHosts) {
+ if (!StringUtils.hasText(deniedHosts)) {
+ throw new IllegalArgumentException("deniedHosts argument cannot be null or empty.");
+ }
+ }
+
+ protected boolean isIpv4Candidate(String host) {
+ String[] quads = StringUtils.tokenizeToStringArray(host, ".");
+ if (quads == null || quads.length != 4) {
+ return false;
+ }
+ for (String quad : quads) {
+ if (!quad.equals("*")) {
+ try {
+ Integer.parseInt(quad);
+ } catch (NumberFormatException nfe) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
+ throw new UnsupportedOperationException("Not yet fully implemented!!!" );
+ }
+}
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HostFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.java?rev=948527&r1=948526&r2=948527&view=diff
==============================================================================
--- incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.java (original)
+++ incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.java Wed May 26 18:34:28 2010
@@ -1,269 +1,269 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.shiro.web.filter.authz;
-
-import org.apache.shiro.util.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A filter that translates an HTTP Request's Method (eg GET, POST, etc)
- * into an corresponding action (verb) and uses that verb to construct a permission that will be checked to determine
- * access.
- * <p/>
- * This Filter is primarily provided to support REST environments where the type (Method)
- * of request translates to an action being performed on one or more resources. This paradigm works well with Shiro's
- * concepts of using permissions for access control and can be leveraged to easily perform permission checks.
- * <p/>
- * This filter functions as follows:
- * <ol>
- * <li>The incoming HTTP request's Method (GET, POST, PUT, DELETE, etc) is discovered.</li>
- * <li>The Method is translated into a more 'application friendly' verb, such as 'create', edit', 'delete', etc.</li>
- * <li>The verb is appended to any configured permissions for the
- * {@link org.apache.shiro.web.filter.PathMatchingFilter currently matching path}.</li>
- * <li>If the current {@code Subject} {@link org.apache.shiro.subject.Subject#isPermitted(String) isPermitted} to
- * perform the resolved action, the request is allowed to continue.</li>
- * </ol>
- * <p/>
- * For example, if the following filter chain was defined, where 'rest' was the name given to a filter instance of
- * this class:
- * <pre>
- * /user/** = rest[user]</pre>
- * Then an HTTP {@code GET} request to {@code /user/1234} would translate to the constructed permission
- * {@code user:read} (GET is mapped to the 'read' action) and execute the permission check
- * <code>Subject.isPermitted("user:read")</code> in order to allow the request to continue.
- * <p/>
- * Similarly, an HTTP {@code POST} to {@code /user} would translate to the constructed permission
- * {@code user:create} (POST is mapped to the 'create' action) and execute the permission check
- * <code>Subject.isPermitted("user:create")</code> in order to allow the request to continue.
- * <p/>
- * <h3>Method To Verb Mapping</h3>
- * The following table represents the default HTTP Method-to-action verb mapping:
- * <table>
- * <tr><th>HTTP Method</th><th>Mapped Action</th><th>Example Permission</th><th>Runtime Check</th></tr>
- * <tr><td>head</td><td>read</td><td>perm1</td><td>perm1:read</td></tr>
- * <tr><td>get</td><td>read</td><td>perm2</td><td>perm2:read</td></tr>
- * <tr><td>put</td><td>update</td><td>perm3</td><td>perm3:update</td></tr>
- * <tr><td>post</td><td>create</td><td>perm4</td><td>perm4:create</td></tr>
- * <tr><td>mkcol</td><td>create</td><td>perm5</td><td>perm5:create</td></tr>
- * <tr><td>options</td><td>read</td><td>perm6</td><td>perm6:read</td></tr>
- * <tr><td>trace</td><td>read</td><td>perm7</td><td>perm7:read</td></tr>
- * </table>
- *
- * @author Brian Demers
- * @author Tamas Cservenak
- * @author Les Hazlewood
- * @since 1.0
- */
-public class HttpMethodPermissionFilter extends PermissionsAuthorizationFilter {
-
- /**
- * This class's private logger.
- */
- private static final Logger log = LoggerFactory.getLogger(HttpMethodPermissionFilter.class);
-
- /**
- * Map that contains a mapping between http methods to permission actions (verbs)
- */
- private final Map<String, String> httpMethodActions = new HashMap<String, String>();
-
- //Actions representing HTTP Method values (GET -> read, POST -> create, etc)
- private static final String CREATE_ACTION = "create";
- private static final String READ_ACTION = "read";
- private static final String UPDATE_ACTION = "update";
- private static final String DELETE_ACTION = "delete";
-
- /**
- * Enum of constants for well-defined mapping values. Used in the Filter's constructor to perform the map instance
- * used at runtime.
- */
- private static enum HttpMethodAction {
-
- DELETE(DELETE_ACTION),
- GET(READ_ACTION),
- HEAD(READ_ACTION),
- MKCOL(CREATE_ACTION), //webdav, but useful here
- OPTIONS(READ_ACTION),
- POST(CREATE_ACTION),
- PUT(UPDATE_ACTION),
- TRACE(READ_ACTION);
-
- private final String action;
-
- private HttpMethodAction(String action) {
- this.action = action;
- }
-
- public String getAction() {
- return this.action;
- }
- }
-
- /**
- * Creates the filter instance with default method-to-action values in the instance's
- * {@link #getHttpMethodActions() http method actions map}.
- */
- public HttpMethodPermissionFilter() {
- for (HttpMethodAction methodAction : HttpMethodAction.values()) {
- httpMethodActions.put(methodAction.name().toLowerCase(), methodAction.getAction());
- }
- }
-
- /**
- * Returns the HTTP Method name (key) to action verb (value) mapping used to resolve actions based on an
- * incoming {@code HttpServletRequest}. All keys and values are lower-case. The
- * default key/value pairs are defined in the top class-level JavaDoc.
- *
- * @return the HTTP Method lower-case name (key) to lower-case action verb (value) mapping
- */
- protected Map<String, String> getHttpMethodActions() {
- return this.httpMethodActions;
- }
-
- /**
- * Determines the action (verb) attempting to be performed on the filtered resource by the current request.
- * <p/>
- * This implementation expects the incoming request to be an {@link HttpServletRequest} and returns a mapped
- * action based on the HTTP request {@link javax.servlet.http.HttpServletRequest#getMethod() method}.
- *
- * @param request to pull the method from.
- * @return The string equivalent verb of the http method.
- */
- protected String getHttpMethodAction(ServletRequest request) {
- String method = ((HttpServletRequest) request).getMethod();
- return getHttpMethodAction(method);
- }
-
- /**
- * Determines the corresponding application action that will be performed on the filtered resource based on the
- * specified HTTP method (GET, POST, etc).
- *
- * @param method to be translated into the verb.
- * @return The string equivalent verb of the method.
- */
- protected String getHttpMethodAction(String method) {
- String lc = method.toLowerCase();
- String resolved = getHttpMethodActions().get(lc);
- return resolved != null ? resolved : method;
- }
-
- /**
- * Returns a collection of String permissions with which to perform a permission check to determine if the filter
- * will allow the request to continue.
- * <p/>
- * This implementation merely delegates to {@link #buildPermissions(String[], String)} and ignores the inbound
- * HTTP servlet request, but it can be overridden by subclasses for more complex request-specific building logic
- * if necessary.
- *
- * @param request the inbound HTTP request - ignored in this implementation, but available to
- * subclasses for more complex construction building logic if necessary
- * @param configuredPerms any url-specific permissions mapped to this filter in the URL rules mappings.
- * @param action the application-friendly action (verb) resolved based on the HTTP Method name.
- * @return a collection of String permissions with which to perform a permission check to determine if the filter
- * will allow the request to continue.
- */
- protected String[] buildPermissions(HttpServletRequest request, String[] configuredPerms, String action) {
- return buildPermissions(configuredPerms, action);
- }
-
- /**
- * Builds a new array of permission strings based on the original argument, appending the specified action verb
- * to each one per {@link org.apache.shiro.authz.permission.WildcardPermission WildcardPermission} conventions. The
- * built permission strings will be the ones used at runtime during the permission check that determines if filter
- * access should be allowed to continue or not.
- * <p/>
- * For example, if the {@code configuredPerms} argument contains the following 3 permission strings:
- * <p/>
- * <ol>
- * <li>permission:one</li>
- * <li>permission:two</li>
- * <li>permission:three</li>
- * </ol>
- * And the action is {@code read}, then the return value will be:
- * <ol>
- * <li>permission:one:read</li>
- * <li>permission:two:read</li>
- * <li>permission:three:read</li>
- * </ol>
- * per {@link org.apache.shiro.authz.permission.WildcardPermission WildcardPermission} conventions. Subclasses
- * are of course free to override this method or the
- * {@link #buildPermissions(javax.servlet.http.HttpServletRequest, String[], String) buildPermissions} request
- * variant for custom building logic or with different permission formats.
- *
- * @param configuredPerms list of configuredPerms to be converted.
- * @param action the resolved action based on the request method to be appended to permission strings.
- * @return an array of permission strings with each element appended with the action.
- */
- protected String[] buildPermissions(String[] configuredPerms, String action) {
- if (configuredPerms == null || configuredPerms.length <= 0 || !StringUtils.hasText(action)) {
- return configuredPerms;
- }
-
- String[] mappedPerms = new String[configuredPerms.length];
-
- // loop and append :action
- for (int i = 0; i < configuredPerms.length; i++) {
- mappedPerms[i] = configuredPerms[i] + ":" + action;
- }
-
- if (log.isTraceEnabled()) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < mappedPerms.length; i++) {
- if (i > 0) {
- sb.append(", ");
- }
- sb.append(mappedPerms[i]);
- }
- log.trace("MAPPED '{}' action to permission(s) '{}'", action, sb);
- }
-
- return mappedPerms;
- }
-
- /**
- * Resolves an 'application friendly' action verb based on the {@code HttpServletRequest}'s method, appends that
- * action to each configured permission (the {@code mappedValue} argument is a {@code String[]} array), and
- * delegates the permission check for the newly constructed permission(s) to the superclass
- * {@link PermissionsAuthorizationFilter#isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed}
- * implementation to perform the actual permission check.
- *
- * @param request the inbound {@code ServletRequest}
- * @param response the outbound {@code ServletResponse}
- * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings.
- * @return {@code true} if the request should proceed through the filter normally, {@code false} if the
- * request should be processed by this filter's
- * {@link #onAccessDenied(ServletRequest,ServletResponse,Object)} method instead.
- * @throws IOException
- */
- @Override
- public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
- String[] perms = (String[]) mappedValue;
- // append the http action to the end of the permissions and then back to super
- String action = getHttpMethodAction(request);
- String[] resolvedPerms = buildPermissions(perms, action);
- return super.isAccessAllowed(request, response, resolvedPerms);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.shiro.web.filter.authz;
+
+import org.apache.shiro.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A filter that translates an HTTP Request's Method (eg GET, POST, etc)
+ * into an corresponding action (verb) and uses that verb to construct a permission that will be checked to determine
+ * access.
+ * <p/>
+ * This Filter is primarily provided to support REST environments where the type (Method)
+ * of request translates to an action being performed on one or more resources. This paradigm works well with Shiro's
+ * concepts of using permissions for access control and can be leveraged to easily perform permission checks.
+ * <p/>
+ * This filter functions as follows:
+ * <ol>
+ * <li>The incoming HTTP request's Method (GET, POST, PUT, DELETE, etc) is discovered.</li>
+ * <li>The Method is translated into a more 'application friendly' verb, such as 'create', edit', 'delete', etc.</li>
+ * <li>The verb is appended to any configured permissions for the
+ * {@link org.apache.shiro.web.filter.PathMatchingFilter currently matching path}.</li>
+ * <li>If the current {@code Subject} {@link org.apache.shiro.subject.Subject#isPermitted(String) isPermitted} to
+ * perform the resolved action, the request is allowed to continue.</li>
+ * </ol>
+ * <p/>
+ * For example, if the following filter chain was defined, where 'rest' was the name given to a filter instance of
+ * this class:
+ * <pre>
+ * /user/** = rest[user]</pre>
+ * Then an HTTP {@code GET} request to {@code /user/1234} would translate to the constructed permission
+ * {@code user:read} (GET is mapped to the 'read' action) and execute the permission check
+ * <code>Subject.isPermitted("user:read")</code> in order to allow the request to continue.
+ * <p/>
+ * Similarly, an HTTP {@code POST} to {@code /user} would translate to the constructed permission
+ * {@code user:create} (POST is mapped to the 'create' action) and execute the permission check
+ * <code>Subject.isPermitted("user:create")</code> in order to allow the request to continue.
+ * <p/>
+ * <h3>Method To Verb Mapping</h3>
+ * The following table represents the default HTTP Method-to-action verb mapping:
+ * <table>
+ * <tr><th>HTTP Method</th><th>Mapped Action</th><th>Example Permission</th><th>Runtime Check</th></tr>
+ * <tr><td>head</td><td>read</td><td>perm1</td><td>perm1:read</td></tr>
+ * <tr><td>get</td><td>read</td><td>perm2</td><td>perm2:read</td></tr>
+ * <tr><td>put</td><td>update</td><td>perm3</td><td>perm3:update</td></tr>
+ * <tr><td>post</td><td>create</td><td>perm4</td><td>perm4:create</td></tr>
+ * <tr><td>mkcol</td><td>create</td><td>perm5</td><td>perm5:create</td></tr>
+ * <tr><td>options</td><td>read</td><td>perm6</td><td>perm6:read</td></tr>
+ * <tr><td>trace</td><td>read</td><td>perm7</td><td>perm7:read</td></tr>
+ * </table>
+ *
+ * @author Brian Demers
+ * @author Tamas Cservenak
+ * @author Les Hazlewood
+ * @since 1.0
+ */
+public class HttpMethodPermissionFilter extends PermissionsAuthorizationFilter {
+
+ /**
+ * This class's private logger.
+ */
+ private static final Logger log = LoggerFactory.getLogger(HttpMethodPermissionFilter.class);
+
+ /**
+ * Map that contains a mapping between http methods to permission actions (verbs)
+ */
+ private final Map<String, String> httpMethodActions = new HashMap<String, String>();
+
+ //Actions representing HTTP Method values (GET -> read, POST -> create, etc)
+ private static final String CREATE_ACTION = "create";
+ private static final String READ_ACTION = "read";
+ private static final String UPDATE_ACTION = "update";
+ private static final String DELETE_ACTION = "delete";
+
+ /**
+ * Enum of constants for well-defined mapping values. Used in the Filter's constructor to perform the map instance
+ * used at runtime.
+ */
+ private static enum HttpMethodAction {
+
+ DELETE(DELETE_ACTION),
+ GET(READ_ACTION),
+ HEAD(READ_ACTION),
+ MKCOL(CREATE_ACTION), //webdav, but useful here
+ OPTIONS(READ_ACTION),
+ POST(CREATE_ACTION),
+ PUT(UPDATE_ACTION),
+ TRACE(READ_ACTION);
+
+ private final String action;
+
+ private HttpMethodAction(String action) {
+ this.action = action;
+ }
+
+ public String getAction() {
+ return this.action;
+ }
+ }
+
+ /**
+ * Creates the filter instance with default method-to-action values in the instance's
+ * {@link #getHttpMethodActions() http method actions map}.
+ */
+ public HttpMethodPermissionFilter() {
+ for (HttpMethodAction methodAction : HttpMethodAction.values()) {
+ httpMethodActions.put(methodAction.name().toLowerCase(), methodAction.getAction());
+ }
+ }
+
+ /**
+ * Returns the HTTP Method name (key) to action verb (value) mapping used to resolve actions based on an
+ * incoming {@code HttpServletRequest}. All keys and values are lower-case. The
+ * default key/value pairs are defined in the top class-level JavaDoc.
+ *
+ * @return the HTTP Method lower-case name (key) to lower-case action verb (value) mapping
+ */
+ protected Map<String, String> getHttpMethodActions() {
+ return this.httpMethodActions;
+ }
+
+ /**
+ * Determines the action (verb) attempting to be performed on the filtered resource by the current request.
+ * <p/>
+ * This implementation expects the incoming request to be an {@link HttpServletRequest} and returns a mapped
+ * action based on the HTTP request {@link javax.servlet.http.HttpServletRequest#getMethod() method}.
+ *
+ * @param request to pull the method from.
+ * @return The string equivalent verb of the http method.
+ */
+ protected String getHttpMethodAction(ServletRequest request) {
+ String method = ((HttpServletRequest) request).getMethod();
+ return getHttpMethodAction(method);
+ }
+
+ /**
+ * Determines the corresponding application action that will be performed on the filtered resource based on the
+ * specified HTTP method (GET, POST, etc).
+ *
+ * @param method to be translated into the verb.
+ * @return The string equivalent verb of the method.
+ */
+ protected String getHttpMethodAction(String method) {
+ String lc = method.toLowerCase();
+ String resolved = getHttpMethodActions().get(lc);
+ return resolved != null ? resolved : method;
+ }
+
+ /**
+ * Returns a collection of String permissions with which to perform a permission check to determine if the filter
+ * will allow the request to continue.
+ * <p/>
+ * This implementation merely delegates to {@link #buildPermissions(String[], String)} and ignores the inbound
+ * HTTP servlet request, but it can be overridden by subclasses for more complex request-specific building logic
+ * if necessary.
+ *
+ * @param request the inbound HTTP request - ignored in this implementation, but available to
+ * subclasses for more complex construction building logic if necessary
+ * @param configuredPerms any url-specific permissions mapped to this filter in the URL rules mappings.
+ * @param action the application-friendly action (verb) resolved based on the HTTP Method name.
+ * @return a collection of String permissions with which to perform a permission check to determine if the filter
+ * will allow the request to continue.
+ */
+ protected String[] buildPermissions(HttpServletRequest request, String[] configuredPerms, String action) {
+ return buildPermissions(configuredPerms, action);
+ }
+
+ /**
+ * Builds a new array of permission strings based on the original argument, appending the specified action verb
+ * to each one per {@link org.apache.shiro.authz.permission.WildcardPermission WildcardPermission} conventions. The
+ * built permission strings will be the ones used at runtime during the permission check that determines if filter
+ * access should be allowed to continue or not.
+ * <p/>
+ * For example, if the {@code configuredPerms} argument contains the following 3 permission strings:
+ * <p/>
+ * <ol>
+ * <li>permission:one</li>
+ * <li>permission:two</li>
+ * <li>permission:three</li>
+ * </ol>
+ * And the action is {@code read}, then the return value will be:
+ * <ol>
+ * <li>permission:one:read</li>
+ * <li>permission:two:read</li>
+ * <li>permission:three:read</li>
+ * </ol>
+ * per {@link org.apache.shiro.authz.permission.WildcardPermission WildcardPermission} conventions. Subclasses
+ * are of course free to override this method or the
+ * {@link #buildPermissions(javax.servlet.http.HttpServletRequest, String[], String) buildPermissions} request
+ * variant for custom building logic or with different permission formats.
+ *
+ * @param configuredPerms list of configuredPerms to be converted.
+ * @param action the resolved action based on the request method to be appended to permission strings.
+ * @return an array of permission strings with each element appended with the action.
+ */
+ protected String[] buildPermissions(String[] configuredPerms, String action) {
+ if (configuredPerms == null || configuredPerms.length <= 0 || !StringUtils.hasText(action)) {
+ return configuredPerms;
+ }
+
+ String[] mappedPerms = new String[configuredPerms.length];
+
+ // loop and append :action
+ for (int i = 0; i < configuredPerms.length; i++) {
+ mappedPerms[i] = configuredPerms[i] + ":" + action;
+ }
+
+ if (log.isTraceEnabled()) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < mappedPerms.length; i++) {
+ if (i > 0) {
+ sb.append(", ");
+ }
+ sb.append(mappedPerms[i]);
+ }
+ log.trace("MAPPED '{}' action to permission(s) '{}'", action, sb);
+ }
+
+ return mappedPerms;
+ }
+
+ /**
+ * Resolves an 'application friendly' action verb based on the {@code HttpServletRequest}'s method, appends that
+ * action to each configured permission (the {@code mappedValue} argument is a {@code String[]} array), and
+ * delegates the permission check for the newly constructed permission(s) to the superclass
+ * {@link PermissionsAuthorizationFilter#isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed}
+ * implementation to perform the actual permission check.
+ *
+ * @param request the inbound {@code ServletRequest}
+ * @param response the outbound {@code ServletResponse}
+ * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings.
+ * @return {@code true} if the request should proceed through the filter normally, {@code false} if the
+ * request should be processed by this filter's
+ * {@link #onAccessDenied(ServletRequest,ServletResponse,Object)} method instead.
+ * @throws IOException
+ */
+ @Override
+ public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
+ String[] perms = (String[]) mappedValue;
+ // append the http action to the end of the permissions and then back to super
+ String action = getHttpMethodAction(request);
+ String[] resolvedPerms = buildPermissions(perms, action);
+ return super.isAccessAllowed(request, response, resolvedPerms);
+ }
+}
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/PermissionsAuthorizationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/PortFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/RolesAuthorizationFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/SslFilter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/authz/package-info.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/shiro/trunk/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilter.java
------------------------------------------------------------------------------
svn:eol-style = native