1 Star 1 Fork 0

subpu / jforum.orize

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

jforum.orize

介绍

在请求时通过过滤器来验证请求的地址是否符合资源定义中的规则. 若符合再进行用户角色匹配, 目前支持:全匹配(一个用户有多个角色), 单匹配(一个用户只有一个角色)

安装教程

1. 项目基于jdk8开发. 低于这个版本无法运行。
2. 项目依赖(Maven)
<!-- Orize 注解扫描用到的依赖 -->
<dependency>
	<groupId>org.reflections</groupId>
	<artifactId>reflections</artifactId>
	<version>0.9.12</version>
</dependency>
<!-- JAXB 的EclipseLink moxy实现 -->
<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>org.eclipse.persistence.moxy</artifactId>
	<version>2.7.1</version>
</dependency>
<dependency>
	<groupId>javax.xml.bind</groupId>
	<artifactId>jaxb-api</artifactId>
	<version>2.2.11</version>
</dependency>
<!-- XPath2的实现 -->
<dependency>
	<groupId>net.sf.saxon</groupId>
	<artifactId>Saxon-HE</artifactId>
	<version>10.5</version>
</dependency>

请保证使用Orize的项目中具有这些jar包。

3. SpringBoot使用超容易:jforum.orize.starter

基于SpringBoot(2.3.3. 版本无所谓了)的自动装配,示例项目: jforum2的分支:boot-orize

4. 非SpringBoot的SpringMVC

示例项目: jforum的分支:orize

使用说明

1. 定义需要验证的资源. 目前支持:xml,json,注解。资源定义(xml/json)文件需要放在WEB-INF的目录下
xml结构如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <resources stamp="20210805">
    <item>
      <path>/orders/list</path>
      <method>get</method>
      <action>VIEW</action>
      <roles>Member</roles>
      <spot>do</spot>
    </item>
   ...
 </resources>
json结构如下:
{
  "resources" : {
    "stamp" : "20210805",
     "item" : [ {
       "path" : "/orders/list",
       "method" : "get",
       "action" : "VIEW",
       "roles" : "Member",
       "spot" : "do"
     }, ...
    ]
   }
}
注解:

需要在负责完成请求的方法上增加注解: Orize,例:

@GetMapping(path="/{path}.xhtml")
@Orize(roles={"GUEST", "ADMIN", "MEMBER"}, method="GET", action={OrizeAction.VIEW})
public String boardHome(){}

注意:当一个方法同时负责新增和编辑操作时注解需要如下使用

@PostMapping(path = "/edit")
@Orize(roles={"GUEST", "ADMIN", "MEMBER"}, method="POST", action={OrizeAction.ADD, OrizeAction.EDIT}, spot="action")
public String editBoardPage(){}

上面的示例表示新增时地址如下:

/edit?action=add

编辑时地址如下:

/edit?action=edit

以此来达到区分同一个请求路径表示哪个具体的操作. 若一个地址只完成一个操作不需要使用spot查询参数Key,若spot的值等于do可以忽略(默认值)

扫描注解(Orize)资源定义需要实现: OrizeAnnotationScanner, 以下示例为SpringMVC的实现

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OrizeAnnotationSpringScanner extends OrizeAnnotationScanner {

    @Override
    protected List<String> parsePath(Method method) {
        Stream<String> _methodPath = Stream.empty(), _classPath = Stream.empty();
        GetMapping getAnno = method.getAnnotation(GetMapping.class);
        if(null != getAnno){
            String[] getMethodPath = getAnno.path();
            String[] getMethodValue = getAnno.value();

            _methodPath = Stream.concat(Stream.of(getMethodPath), Stream.of(getMethodValue));
        }
        PostMapping postAnno = method.getAnnotation(PostMapping.class);
        if(null != postAnno){
            String[] postMethodPath = postAnno.path();
            String[] postMethodValue = postAnno.value();

            _methodPath = Stream.concat(Stream.of(postMethodPath), Stream.of(postMethodValue));
        }
        //
        Class<?> aClass = method.getDeclaringClass();
        RequestMapping _crm = aClass.getAnnotation(RequestMapping.class);
        if(null != _crm){
            String[] classPathPrefix = _crm.path();
            String[] classValPrefix = _crm.value();
            _classPath = Stream.concat(Stream.of(classPathPrefix), Stream.of(classValPrefix));
        }

        return OrizeAnnotationScanner.cartesian(
                _methodPath.collect(Collectors.toList()),
                _classPath.collect(Collectors.toList()),
                OrizeAnnotationScanner.mergePathFun);
    }
}
2. 实现用户信息查询接口: OrizeMemberQuery

示例:

/**
 * OrizeMemberQuery的实现
 */
public class OrizeMemberQueryImpl implements OrizeMemberQuery {
    @Override
    public OrizeMember query(HttpServletRequest request) {
        //ETC
    }
}

强烈不建议每次都从数据库(关系型数据库)中获取

3. 配置过滤器

(web.xml)示例如下:

<filter>
	<filter-name>OrizeAuthServletFilter</filter-name>
	<filter-class>com.apobates.forum.orize.servlet.OrizeAuthServletFilter</filter-class>
	<init-param>
            <param-name>loader</param-name>
            <param-value>xml</param-value>
	</init-param>
	<init-param>
            <param-name>path</param-name>
            <param-value>resouces.xml</param-value>
	</init-param>
	<init-param>
            <param-name>queryClass</param-name>
            <param-value>x.y.z.OrizeMemberQueryImpl</param-value>
	</init-param>
	<init-param>
            <param-name>roleMatch</param-name>
            <param-value>any</param-value>
	</init-param>
	<init-param>
            <param-name>ignoreDomain</param-name>
            <param-value>cdn.subpu.com</param-value>
	</init-param>
	<init-param>
            <param-name>ignorePath</param-name>
            <param-value>/static/**</param-value>
	</init-param>
	<init-param>
            <param-name>ignoreExt</param-name>
            <param-value>js,css,png,svg,gif,jpg</param-value>
	</init-param>
</filter>
<filter-mapping>
        <filter-name>OrizeAuthServletFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

init-param说明:

loader: 支持:xml,json,anno; 根据值不同使用不同的资源加载器

path:资源所在的位置,需要放到WEB-INF目录下

queryClass:OrizeMemberQuery实现类的类全名, 实现类中需要有无参的构造器

roleMatch:用户角色的匹配规则, any(单角色匹配),all(多角色匹配)

ignoreDomain: 忽略的域名, 只要请求来自这些域名不进行验证. 多个之间用逗号分隔, 可选项(没有可以不设置此参数) 支持以下几种模式:

*.a.com, a.com, cdn.a.com

ignorePath: 忽略的请求路径, 只要请求路径符合定义不进行验证. 多个之间用逗号分隔, 可选项(没有可以不设置此参数) 支持以下几种模式:

/static, /static/*, /static/*/*.css, /static/**

ignoreExt: 忽略的请求文件扩展名, 只要请求文件符合定义不进行验证. 多个之间用逗号分隔, 可选项(没有可以不设置此参数)

其它说明

1. SpringMVC不建议使用OrizeAuthServletFilter.

项目提供了一个包装类: com.apobates.forum.member.strategy.spring.OrizeAuthHelper 使用示例如下:

/**
 * 实现Orize过滤器
 */
public class OrizeAuthSpringInterceptorImpl extends HandlerInterceptorAdapter {
    @Autowired
    private OrizeAuthHelper orizeAuthHelper;
    @Autowired
    private OrizeMemberRolePredicate memberRolePredicate;
    @Value("${site.orize.log}")
    private String orizeResultLog;
    
    /**
     * 预处理回调方法,实现处理器的预处理(如检查登陆),第三个参数为响应的处理器,自定义Controller
     * 返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws java.lang.Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ImmutablePair<Boolean, Map> ips = orizeAuthHelper.verify(memberRolePredicate, request);
        if(!ips.getLeft()){
            String redirectPath = request.getContextPath() + orizeResultLog; // 验证失败时的提示地址;
            FlashMap flashMap = new FlashMap();
            flashMap.put("errors", ips.getRight().get("message"));
            flashMap.put("method", ips.getRight().get("reqMethod"));
            flashMap.put("path", ips.getRight().get("reqPath"));
            flashMap.setTargetRequestPath(redirectPath);
            FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
            flashMapManager.saveOutputFlashMap(flashMap, request, response);
            response.sendRedirect(redirectPath);
            return false;
        }
        return true;
    }
    //ETC
}

SpringMVC的忽略参数设置:

//不需要验证的配置
@Bean(name="cusIgnoreConfig")
public OrizeAuthIgnoreConfig getIgnoreConfig(){
	return OrizeAuthIgnoreConfig
			.defaultInstance()
			.setIgnoreMediaType("js", "css", "png", "svg", "gif", "jpg");
}
//资源验证助手类
@Bean(name="orizeAuthHelper")
public OrizeAuthHelper getAuthHelper(@NotNull OrizeMemberQuery memberQuery, @Nullable OrizeAuthIgnoreConfig cusIgnoreConfig, ServletContext sc){
	return OrizeAuthHelper
			.defaultInstance("anno", sc)
			.setMemberQuery(memberQuery)
			.setIgnoreConfig(cusIgnoreConfig)
			.build();
        //手动生成资源定义
        //return OrizeAuthHelper.defaultInstance("xml", sc).setNotAnnoResourcePath("resources.xml").setMemberQuery(memberQuery).setIgnoreConfig(cusIgnoreConfig).build();
}
2. 项目不提供角色定义。

用户角色的验证规则只提供抽像的实现: any(OrizeMemberRoleAnyContainsPredicate),all(OrizeMemberRoleContainsAllPredicate),若这两个抽像不满足您的需求可以自行实现: OrizeMemberRolePredicater

/**
 * 用户角色验证谓词表达式
 */
public interface OrizeMemberRolePredicate {
    /**
     * 返回验证OrizeMember的谓词表达式
     *
     * @return 第一个参数: OrizeMember 用户信息, 第二个参数: 资源中定义的角色要求
     */
    BiPredicate<OrizeMember,String[]> getPredicate();
}
3. 关于资源定义中的路径包含占位符

项目暂时只支持全模式匹配, 不支持通配符匹配. 例:

//资源定义: /board/volumes/{path}.xhtml

//匹配请求地址
/board/volumes/20210810.xhtml

//不匹配请求地址
/board/2020/20210810.xhtml

为了支持占位符Orize注解增加两个新方法

/**
 * 注解.用于收集资源的定义
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Orize {
    /**
     * 路径中是否存在占位符
     * 例:
     * /{id}.xhtml 存在
     * /edit 不存在
     * @return true存在/false不存在
     */
    boolean slot()default false;

    /**
     * 若存在占位符,占位的名称是什么
     * 例:/{id}.xhtml, slotKeys={"id"}
     * @return
     */
    String[] slotKeys()default {"*"};
    
    //ETC
}

SpringMVC控制器方法示例:

@GetMapping(path="/{path}.xhtml")
@Orize(roles={"NO","BM","MASTER","ADMIN"}, method="get", action={OrizeAction.VIEW}, slot = true, slotKeys = {"path"})
public String volumeHome(){}
4. 关于xml和json文件的生成

在项目中提供了一个示例: com.apobates.forum.orize.servlet.OrizeResourceGenTest.

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.

简介

请求地址验证. 展开 收起
Java
Apache-2.0
取消

发行版 (1)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/subpu/jforum.orize.git
git@gitee.com:subpu/jforum.orize.git
subpu
jforum.orize
jforum.orize
master

搜索帮助