[home]开源官网初始化
This commit is contained in:
22
home/i18n/en/docusaurus-plugin-content-docs/current.json
Normal file
22
home/i18n/en/docusaurus-plugin-content-docs/current.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"version.label": {
|
||||
"message": "下一篇",
|
||||
"description": "The label for version current"
|
||||
},
|
||||
"sidebar.docs.category.Guides": {
|
||||
"message": "入门",
|
||||
"description": "The label for category Guides in sidebar docs"
|
||||
},
|
||||
"sidebar.docs.category.Advanced": {
|
||||
"message": "进阶扩展",
|
||||
"description": "The label for category Advanced in sidebar docs"
|
||||
},
|
||||
"sidebar.docs.category.Integrate": {
|
||||
"message": "集成案例",
|
||||
"description": "The label for category Integrate in sidebar docs"
|
||||
},
|
||||
"sidebar.docs.category.Others": {
|
||||
"message": "其它",
|
||||
"description": "The label for category Others in sidebar docs"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: custom-datasource
|
||||
title: 自定义数据源
|
||||
sidebar_label: 自定义数据源
|
||||
---
|
||||
|
||||
## 自定义数据源
|
||||
|
||||
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
|
||||
|
||||
- `PathTreeProvider`: 资源的数据源接口,实现从数据库,文本等加载数据,加载到对应的资源权限匹配器`DefaultPathRoleMatcher`中
|
||||
- `SurenessAccountProvider`: 用户的账户密钥信息接口,实现从数据库,文本等加载数据,加载到需要账户数据的`processor`中
|
||||
|
||||
|
||||
首先我们先来认识下sureness提供的两个用户信息和资源权限信息的接口,用户可以实现这些接口自定义从不同的数据源给sureness提供数据。
|
||||
当我们把项目从配置文件模式切换成数据库模式时,也只是简单替换了这些接口的实现类而已。
|
||||
|
||||
一. `PathTreeProvider` 资源权限配置信息的数据源接口,我们可以实现从数据库,文本等加载接口想要的资源权限配置数据
|
||||
|
||||
````
|
||||
public interface PathTreeProvider {
|
||||
|
||||
Set<String> providePathData();
|
||||
|
||||
Set<String> provideExcludedResource();
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
此接口主要是需要实现上面这两个方法,providePathData是加载资源权限配置信息,也就是我们配置文件模式下sureness.yml的resourceRole信息列,
|
||||
provideExcludedResource是加载哪些资源可以被过滤不认证鉴权,也就是sureness.yml下的excludedResource信息列,如下。
|
||||
|
||||
````
|
||||
resourceRole:
|
||||
- /api/v2/host===post===[role2,role3,role4]
|
||||
- /api/v2/host===get===[role2,role3,role4]
|
||||
- /api/v2/host===delete===[role2,role3,role4]
|
||||
- /api/v2/host===put===[role2,role3,role4]
|
||||
- /api/mi/**===put===[role2,role3,role4]
|
||||
- /api/v1/getSource1===get===[role1,role2]
|
||||
- /api/v2/getSource2/*/*===get===[role2]
|
||||
|
||||
excludedResource:
|
||||
- /api/v1/source3===get
|
||||
- /api/v3/host===get
|
||||
- /**/*.css===get
|
||||
- /**/*.ico===get
|
||||
- /**/*.png===get
|
||||
````
|
||||
|
||||
而当我们使用数据库模式时,实现这些信息从数据库关联读取就ok了,规范返回 eg: /api/v2/host===post===[role2,role3,role4] 格式的数据列,
|
||||
具体的数据库实现类参考类 - [DatabasePathTreeProvider](https://github.com/tomsun28/sureness/blob/master/sample-tom/src/main/java/com/usthe/sureness/sample/tom/sureness/provider/DatabasePathTreeProvider.java)
|
||||
|
||||
二. `SurenessAccountProvider`这第二个相关的接口就是用户的账户密钥信息提供接口,我们需要实现从数据库或者文本等其他数据源那里去加载我们想要的用户的账户信息数据,
|
||||
这些数据提供需要账户数据的processor进行用户的认证。
|
||||
|
||||
````
|
||||
public interface SurenessAccountProvider {
|
||||
SurenessAccount loadAccount(String appId);
|
||||
}
|
||||
````
|
||||
此接口主要需要实现上面这个loadAccount方法,通过用户的唯一标识appid来从数据库或者redis缓存中查找到用户的账户信息返回即可。
|
||||
用户账户信息类SurenessAccount如下:
|
||||
|
||||
````
|
||||
public class DefaultAccount implements SurenessAccount {
|
||||
|
||||
private String appId;
|
||||
private String password;
|
||||
private String salt;
|
||||
private List<String> ownRoles;
|
||||
private boolean disabledAccount;
|
||||
private boolean excessiveAttempts;
|
||||
}
|
||||
````
|
||||
|
||||
比较简单,主要是需要提供用户的密码相关信息即可,供sureness认证时密钥判断正确与否。
|
||||
这个具体的数据库接口实现可参考类 - [DatabaseAccountProvider](https://github.com/tomsun28/sureness/blob/master/sample-tom/src/main/java/com/usthe/sureness/sample/tom/sureness/provider/DatabaseAccountProvider.java)
|
||||
|
||||
|
||||
具体扩展实践请参考 [Springboot项目集成-数据库方案](/docs/integrate/sample-tom)
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
id: custom-processor
|
||||
title: 自定义processor
|
||||
sidebar_label: 自定义processor
|
||||
---
|
||||
|
||||
processor就是对请求的用户账户信息subject真正的认证鉴权处理器,我们需要实现BaseProcessor接口,来实现我们自定义的认证鉴权方式。
|
||||
sureness已经内置基于账户密码认证方式处理PasswordSubject的PasswordProcessor,基于jwt认证方式处理JwtSubject的JwtProcessor等。
|
||||
|
||||
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
|
||||
|
||||
- `Processor`: `Subject`处理接口,根据Subject信息,进行认证鉴权
|
||||
|
||||
```
|
||||
public abstract class BaseProcessor implements Processor{
|
||||
|
||||
public abstract boolean canSupportSubjectClass(Class<?> var);
|
||||
|
||||
public abstract Subject authenticated (Subject var) throws SurenessAuthenticationException;
|
||||
|
||||
public abstract void authorized(Subject var) throws SurenessAuthorizationException;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
上面就是BaseProcessor的一些重要接口方法,自定义processor需要我们去实现这些方法。
|
||||
|
||||
- `canSupportSubjectClass` 判断是否支持入参的此Subject类类型,比如 JwtProcessor只支持JwtSubject, PasswordProcessor只支持PasswordSubject
|
||||
- `authenticated` 对subject进行认证,根据传入的subject信息和系统内信息,进行请求用户的账户认证
|
||||
- `authorized` 对subject进行鉴权,鉴权判断此用户是否拥有其访问api的访问权限
|
||||
|
||||
sureness使用异常流程模型,以上的认证失败或鉴权失败都会抛出不同类型的异常,用户在最外部捕获判断实现接下来的流程。
|
||||
|
||||
sureness默认异常类型参考 [默认异常类型](/docs/start/default-exception)
|
||||
具体扩展实践请参考 [Springboot项目集成-数据库方案](/docs/integrate/sample-tom)
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
id: custom-subject-creator
|
||||
title: 自定义subject creator
|
||||
sidebar_label: 自定义subject creator
|
||||
---
|
||||
|
||||
自定义`subject creator`是我们使用频率最高的扩展,当请求体对象并不是`servlet`或者`jax-rs`标准`api`时,
|
||||
或者我们从request请求的不同地方获取账户信息时,我们就需要自定义`subject creator`,
|
||||
使其通过请求对象获取我们需要的请求信息(请求路径,请求方法,认证信息等), 从而创建出对应的`subject`.
|
||||
|
||||
sureness已经内置能创建出基于账户密码的PasswordSubject的BasicSubjectServletCreator,
|
||||
和创建出jwt类型JwtSubject的JwtSubjectServletCreator等,当然我们可以自定义自己需要的subjectCreator来创建subject
|
||||
|
||||
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
|
||||
|
||||
- `SubjectCreate`: 创建`Subject`接口,根据请求内容创建不同类型的`Subject`对象
|
||||
|
||||
实现`SubjectCreate`接口方法,根据request请求的内容创建出对应需要的的`subject`
|
||||
|
||||
具体扩展实践请参考 [sample-spring-webflux项目集成案例](/docs/integrate/sample-spring-webflux)
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
id: custom-subject
|
||||
title: 自定义subject
|
||||
sidebar_label: 自定义subject
|
||||
---
|
||||
|
||||
subject包含的就是我们request请求所带的用户信息,sureness已经内置基于账户密码的PasswordSubject,
|
||||
基于jwt的JwtSubject等,当然我们可以自定义自己需要的subject来扩充自己的用户信息
|
||||
|
||||
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
|
||||
|
||||
- `Subject`: 认证鉴权对象接口,提供访问对象的账户密钥,请求资源,角色等信息
|
||||
|
||||
自定义subject需要走以下流程:
|
||||
|
||||
1. 实现`Subject`接口,添加自定义的`subject`内容
|
||||
2. 实现`SubjectCreate`接口方法,创建出自定义的`subject` 参考[自定义Subject Creator](/docs/advanced/custom-subject-creator)
|
||||
3. 实现`Processor`接口,支持处理自定义的`subject` 参考[自定义Processor](/docs/advanced/custom-processor)
|
||||
|
||||
具体扩展实践请参考 [使用sureness30分钟项目集成案例](/docs/integrate/sample-tom)
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
id: extend-point
|
||||
title: 进阶扩展
|
||||
sidebar_label: 扩展点
|
||||
---
|
||||
|
||||
`sureness`支持自定义`subject`,自定义注册`subjectCreator`,自定义`processor`处理器,自定义数据源加载器等。
|
||||
|
||||
进阶自定义扩展之前我们先来了解下sureness的大致流程:
|
||||
|
||||

|
||||
|
||||
如上面的流程所讲,Subject被SubjectCreate根据request请求体所创造,不同的认证鉴权处理器Processor来处理所支持的Subject。
|
||||
|
||||
|
||||
sureness提供了下面这些常用接口作为扩展点:
|
||||
|
||||
- `Subject`: 认证鉴权对象接口,提供访问对象的账户密钥,请求资源,角色等信息
|
||||
- `SubjectCreate`: 创建`Subject`接口,根据请求内容创建不同类型的`Subject`对象
|
||||
- `Processor`: `Subject`处理接口,根据Subject信息,进行认证鉴权
|
||||
- `PathTreeProvider`: 资源的数据源接口,实现从数据库,文本等加载数据
|
||||
- `SurenessAccountProvider`: 用户的账户密钥信息接口,实现从数据库,文本等加载数据
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: contributing
|
||||
title: 参与贡献
|
||||
sidebar_label: 参与贡献
|
||||
---
|
||||
|
||||
Contributing to Sureness
|
||||
=======================================
|
||||
Very welcome to Contribute this project, go further and better with sureness.
|
||||
Firstly, thanks for your interest in contributing! I hope that this will be a pleasant first experience for you, and that you will return to continue contributing.
|
||||
|
||||
Components of Repository:
|
||||
- [sureness's kernel code--sureness-core](https://github.com/usthe/sureness/tree/master/core)
|
||||
- [sureness integration springboot sample(configuration file scheme)--sample-bootstrap](https://github.com/usthe/sureness/tree/master/sample-bootstrap)
|
||||
- [sureness integration springboot sample(database scheme)-sample-tom](https://github.com/usthe/sureness/tree/master/sample-tom)
|
||||
- [sample projects using sureness in each framework(javalin,ktor,quarkus)--samples](https://github.com/usthe/sureness/tree/master/samples)
|
||||
|
||||
## How to contribute?
|
||||
|
||||
Most of the contributions that we receive are code contributions, but you can
|
||||
also contribute to the documentation or simply report solid bugs
|
||||
for us to fix.
|
||||
|
||||
For new contributors, please take a look at issues or pull requests with a tag called below.
|
||||
|
||||
[Good first issue](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
||||
[Help wanted](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
|
||||
[Good first pull request](https://github.com/usthe/sureness/issues?q=label%3A%22good+first+pull+request%22+)
|
||||
|
||||
## Join discussion
|
||||
|
||||
[Github Discussion](https://github.com/usthe/sureness/discussions)
|
||||
[Gitter Channel](https://gitter.im/usthe/sureness)
|
||||
|
||||
----
|
||||
----
|
||||
|
||||
参与贡献
|
||||
=======================================
|
||||
|
||||
非常欢迎参与项目贡献,我们致力于维护一个互相帮助的快乐社区。
|
||||
|
||||
仓库的组成部分:
|
||||
- [sureness的核心代码--sureness-core](https://github.com/usthe/sureness/tree/master/core)
|
||||
- [使用sureness集成springboot搭建权限项目(配置文件方案)--sample-bootstrap](https://github.com/usthe/sureness/tree/master/sample-bootstrap)
|
||||
- [使用sureness集成springboot搭建权限项目(数据库方案)--sample-tom](https://github.com/usthe/sureness/tree/master/sample-tom)
|
||||
- [各个框架使用sureness的样例项目(javalin,ktor,quarkus)--samples](https://github.com/usthe/sureness/tree/master/samples)
|
||||
|
||||
|
||||
## 如何贡献?
|
||||
|
||||
我们不仅仅接收代码的贡献提交,您也可以通过提交文档的更新或者BUG的报告来参与社区贡献。
|
||||
|
||||
如果是新的贡献者,请首先了解参考如下样例的提交Issues,提交Pull Requests如果工作。
|
||||
|
||||
[Good first issue](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
||||
[Help wanted](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
|
||||
[Good first pull request](https://github.com/usthe/sureness/issues?q=label%3A%22good+first+pull+request%22+)
|
||||
|
||||
## 加入交流
|
||||
|
||||
[Github Discussion](https://github.com/usthe/sureness/discussions)
|
||||
[Gitter Channel](https://gitter.im/usthe/sureness)
|
||||
QQ交流群:390083213
|
||||
微信公众号:sureness
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
id: design
|
||||
title: 设计文档
|
||||
sidebar_label: 设计文档
|
||||
---
|
||||
|
||||
### 高性能匹配
|
||||
|
||||

|
||||
|
||||
### 处理流程
|
||||
|
||||

|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
id: sample-bootstrap
|
||||
title: Springboot项目集成-配置文件方案
|
||||
sidebar_label: Springboot项目集成-配置文件方案
|
||||
---
|
||||
|
||||
[Springboot项目集成-配置文件方案代码仓库地址](https://github.com/tomsun28/sureness/tree/master/sample-bootstrap)
|
||||
|
||||
- 基于`springboot`
|
||||
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
|
||||
- 使用默认的`sureness-config`
|
||||
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
|
||||
- 保护入口: `SurenessFilterExample`
|
||||
- 推荐使用`postman`测试,测试样例为`sample-bootstrap-postman.json`,导入`postman`即可
|
||||
@@ -0,0 +1,296 @@
|
||||
---
|
||||
id: sample-javalin
|
||||
title: Javalin项目集成
|
||||
sidebar_label: Javalin项目集成
|
||||
---
|
||||
|
||||
|
||||
# Using Sureness to protect the security of Javalin REST API
|
||||
|
||||
[javalin-sureness sample repository](https://github.com/tomsun28/sureness/tree/master/samples/javalin-sureness)
|
||||
|
||||
Using Sureness to secure Javalin REST API by providing authentication(JWT,Basic,Digest) and authorization(RBAC)
|
||||
|
||||
|
||||
## What You Will Learn
|
||||
|
||||
* Creating a simple REST API using Javalin
|
||||
* Learn how to integrate Sureness into a Javalin application
|
||||
* Learn how to issue a JWT
|
||||
* Test API authentication - use JWT Auth, Basic Auth, Digest Auth to test the security of the REST API
|
||||
* Test API authorization - use different users to verify that they can access the REST API
|
||||
|
||||
|
||||
The tutorial assumes that you know what JWT, Basic Auth, Digest Auth, RBAC are. If you
|
||||
do not, then you can check [jwt](https://jwt.io/introduction/), [basic auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_basic.html) , [digest auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_digest.html), [rbac](https://en.wikipedia.org/wiki/Role-based_access_control) for an introduction.
|
||||
|
||||
## Setting Up Dependencies
|
||||
|
||||
First, you will need to create a maven project and add Javalin, Sureness dependencies coordinate
|
||||
|
||||
````
|
||||
<dependency>
|
||||
<groupId>io.javalin</groupId>
|
||||
<artifactId>javalin</artifactId>
|
||||
<version>{{site.javalinversion}}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.usthe.sureness</groupId>
|
||||
<artifactId>sureness-core</artifactId>
|
||||
<version>1.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.30</version>
|
||||
</dependency>
|
||||
````
|
||||
|
||||
|
||||
## Setting Up Javalin and Create REST API
|
||||
|
||||
We need to create a simple Javalin app and provide some REST API for test.
|
||||
|
||||
```
|
||||
// init javalin
|
||||
Javalin app = Javalin.create().start(8088);
|
||||
```
|
||||
|
||||
```
|
||||
// create simple rest api
|
||||
// simple rest api
|
||||
app.routes(() ->
|
||||
path("api", () -> {
|
||||
path("v3", () -> {
|
||||
get("host", ctx -> ctx.result("get /api/v3/host success"));
|
||||
put("book", ctx -> ctx.result("put /api/v3/book success"));
|
||||
});
|
||||
path("v2", () -> {
|
||||
path("host", () -> {
|
||||
get(ctx -> ctx.result("get /api/v2/host success"));
|
||||
post(ctx -> ctx.result("post /api/v2/host success"));
|
||||
put(ctx -> ctx.result("put /api/v2/host success"));
|
||||
delete(ctx -> ctx.result("delete /api/v2/host success"));
|
||||
});
|
||||
});
|
||||
path("v1", () -> {
|
||||
path("source1", () -> {
|
||||
get(ctx -> ctx.result("get /api/v1/source1 success"));
|
||||
post(ctx -> ctx.result("post /api/v1/source1 success"));
|
||||
put(ctx -> ctx.result("put /api/v1/source1 success"));
|
||||
delete(ctx -> ctx.result("delete /api/v1/source1 success"));
|
||||
});
|
||||
});
|
||||
}));
|
||||
```
|
||||
|
||||
|
||||
## Setting Up Sureness
|
||||
|
||||
#### 1. Use the Default Configuration to Configure Sureness
|
||||
|
||||
The default configuration -`DefaultSurenessConfig` uses the document datasource `sureness.yml` as the auth datasource.
|
||||
It supports JWT, Basic Auth, Digest Auth authentication.
|
||||
```
|
||||
public static void main(String[] args) {
|
||||
// init sureness default config
|
||||
new DefaultSurenessConfig();
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Config Document Datasource - `sureness.yml`
|
||||
|
||||
Sureness authentication requires us to provide our own account data, role permission data. These data may come from document, databases,, annotations, etc. When we use sureness default configuration above, the datasource is document - `sureness.yml`.
|
||||
|
||||
Create a file named `sureness.yml` in the `resource` directory. Configure account data, role permission data in the `sureness.yml`. eg:
|
||||
|
||||
````yaml
|
||||
## -- sureness.yml document dataSource-- ##
|
||||
|
||||
# load api resource which need be protected, config role who can access these resource.
|
||||
# resources that are not configured are also authenticated and protected by default, but not authorized
|
||||
# eg: /api/v2/host===post===[role2,role3] means /api/v2/host===post can be access by role2,role3
|
||||
# eg: /api/v1/source2===get===[] means /api/v1/source2===get can not be access by any role
|
||||
resourceRole:
|
||||
- /api/v1/source1===get===[role2]
|
||||
- /api/v1/source1===post===[role1]
|
||||
- /api/v1/source1===delete===[role3]
|
||||
- /api/v1/source1===put===[role1,role2]
|
||||
- /api/v1/source2===get===[]
|
||||
- /api/v2/host===post===[role2,role3]
|
||||
- /api/v2/host===get===[role2,role3]
|
||||
- /api/v2/host===delete===[role2,role3]
|
||||
- /api/v2/host===put===[role2,role3]
|
||||
- /api/v3/*===*===[role1,role2,role3]
|
||||
|
||||
# load api resource which do not need be protected, means them need be excluded.
|
||||
# these api resource can be access by everyone
|
||||
excludedResource:
|
||||
- /api/v3/host===get
|
||||
- /**/*.html===get
|
||||
- /**/*.js===get
|
||||
- /**/*.css===get
|
||||
- /**/*.ico===get
|
||||
|
||||
# account info
|
||||
# there are three account: admin, root, tom
|
||||
# eg: admin has [role1,role2] ROLE, unencrypted password is admin, encrypted password is 0192023A7BBD73250516F069DF18B500
|
||||
# eg: root has role1, unencrypted password is 23456
|
||||
# eg: tom has role3, unencrypted password is 32113
|
||||
account:
|
||||
- appId: admin
|
||||
# if add salt, the password is encrypted password - the result: MD5(password+salt)
|
||||
# digest auth not support encrypted password
|
||||
# if no salt, the password is unencrypted password
|
||||
credential: 0192023A7BBD73250516F069DF18B500
|
||||
salt: 123
|
||||
role: [role1,role2]
|
||||
- appId: root
|
||||
credential: 23456
|
||||
role: [role1,role2]
|
||||
- appId: tom
|
||||
credential: 32113
|
||||
role: [role3]
|
||||
|
||||
````
|
||||
|
||||
|
||||
|
||||
#### 3. Add an Interceptor Intercepting All Requests
|
||||
|
||||
The essence of sureness is to intercept all rest requests for authenticating and authorizing. The interceptor can be a filter or interceptor, it intercepts all request to check them. In Javalin, we use `app.before()`.
|
||||
|
||||
```
|
||||
// intercept all rest requests for authenticating and authorizing
|
||||
app.before(ctx -> {
|
||||
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(ctx.req);
|
||||
// when auth error , the exception throw, you should use app.exception() catch it and define return
|
||||
if (subject != null) {
|
||||
SurenessContextHolder.bindSubject(subject);
|
||||
}
|
||||
});
|
||||
|
||||
app.after(ctx -> SurenessContextHolder.unbindSubject());
|
||||
|
||||
```
|
||||
|
||||
#### 4. Last, Implement Auth Exception Handling Process
|
||||
|
||||
Sureness uses exception handling process:
|
||||
|
||||
- If auth success, method - `checkIn()` will return a `SubjectSum` object containing user information.
|
||||
- If auth failure, method - `checkIn()` will throw different types of auth exceptions.
|
||||
|
||||
We need to continue the subsequent process based on these exceptions.(eg: return the request response)
|
||||
|
||||
Here we need to customize the exceptions thrown by `checkIn`, passed directly when auth success, catch exception when auth failure and do something:
|
||||
|
||||
````
|
||||
// when auth error , the exception throw, you should use app.exception() catch it and define return
|
||||
app.exception(UnknownAccountException.class, (e, ctx) -> {
|
||||
log.debug("this request user account not exist");
|
||||
ctx.status(401).result(e.getMessage());
|
||||
}).exception(IncorrectCredentialsException.class, (e, ctx) -> {
|
||||
log.debug("this account credential is incorrect");
|
||||
ctx.status(401).result(e.getMessage());
|
||||
}).exception(ExpiredCredentialsException.class, (e, ctx) -> {
|
||||
log.debug("this account credential expired");
|
||||
ctx.status(401).result(e.getMessage());
|
||||
}).exception(NeedDigestInfoException.class, (e, ctx) -> {
|
||||
log.debug("you should try once again with digest auth information");
|
||||
ctx.status(401).header("WWW-Authenticate", e.getAuthenticate());
|
||||
}).exception(UnauthorizedException.class, (e, ctx) -> {
|
||||
log.debug("this account can not access this resource");
|
||||
ctx.status(403).result(e.getMessage());
|
||||
}).exception(Exception.class, (e, ctx) -> {
|
||||
log.error("other exception happen: ", e);
|
||||
ctx.status(500).result(e.getMessage());
|
||||
});
|
||||
|
||||
````
|
||||
|
||||
|
||||
## Provide an Issue JWT Api
|
||||
|
||||
Now we provide a REST API to issue JWT. We can use this JWT to test JWT auth.
|
||||
|
||||
````
|
||||
// issue jwt rest api
|
||||
app.get("/auth/token", ctx -> {
|
||||
SubjectSum subjectSum = SurenessContextHolder.getBindSubject();
|
||||
if (subjectSum == null) {
|
||||
ctx.result("Please auth!");
|
||||
} else {
|
||||
String principal = (String) subjectSum.getPrincipal();
|
||||
List<String> roles = (List<String>) subjectSum.getRoles();
|
||||
// issue jwt
|
||||
String jwt = JsonWebTokenUtil.issueJwt(UUID.randomUUID().toString(), principal,
|
||||
"token-server", 3600L, roles);
|
||||
ctx.result(jwt);
|
||||
}
|
||||
});
|
||||
````
|
||||
|
||||
**All done, we can test now!**
|
||||
|
||||
## Test
|
||||
|
||||
Through the above steps, a complete auth function project is completed. Someone maybe think that with only these few steps, where is its complete function and what can it support?
|
||||
This built project is based on the RBAC permission model and supports Baisc authentication, Digest authentication and JWT authentication. It can fine-grained control the user's access to the restful api provided by the Javalin. That is to control which users can access which api.
|
||||
|
||||
Let's test it. (we use postman and chrome to test.)
|
||||
|
||||
### Test Authentication
|
||||
|
||||
#### 1. Basic Auth Test
|
||||
|
||||
Use postman Basic auth, as shown below:
|
||||
|
||||
* success - input username: admin, password: admin
|
||||
|
||||

|
||||
|
||||
|
||||
* fail - input username: admin, password: 12345
|
||||
|
||||

|
||||
|
||||
#### 2. Digest Auth Test
|
||||
|
||||
Note: If password has been encrypted, Digest auth not support.(So the account admin not support Digest auth).
|
||||
Use chrome to Digest auth, as shown below:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
#### 3. JWT Auth Test
|
||||
|
||||
First, we should access **[GET /auth/token]** api to get a JWT to use, as shown below:
|
||||
|
||||

|
||||
|
||||
Then, use the JWT as Bearer Token to access REST API, as shown below:
|
||||
|
||||

|
||||
|
||||
|
||||
### Test Authorization
|
||||
|
||||
* success - user **tom** has role **role3**, the api **[DELETE - /api/v2/host]** support **role3** access, so **tom** can access api **[DELETE - /api/v2/host]** success, as shown below:
|
||||
|
||||

|
||||
|
||||
|
||||
* fail - user **tom** only has role **role3**, the api **[GET - /api/v1/source1]** only support **role2** access, not support **role3**, so **tom** can not access api **[GET - /api/v1/source1]**, as shown below:
|
||||
|
||||

|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
Javalin is a framework dedicated to simplicity and ease of use, and so is Sureness.
|
||||
We hope you enjoy this tutorial. Of course, the tutorial only introduces a simple introduction. Our account data, role permission data can not only be written in `sureness.yml`, but also loaded and obtained from the database and annotations. We can also customize the authentication method, data source, etc.
|
||||
Finally, thank you again for reading.
|
||||
|
||||
[DEMO SOURCE CODE ON GITHUB](https://github.com/usthe/sureness/tree/master/samples/javalin-sureness)
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
id: sample-ktor
|
||||
title: Ktor项目集成
|
||||
sidebar_label: Ktor项目集成
|
||||
---
|
||||
|
||||
[ktor-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/ktor-sureness)
|
||||
|
||||
- 基于`ktor, servlet`
|
||||
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
|
||||
- 使用默认的`sureness-config`
|
||||
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
|
||||
- 例子中包含`REST API`
|
||||
- 保护入口: `Application.kt`
|
||||
- 推荐使用`postman`测试
|
||||
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
---
|
||||
id: sample-micronaut
|
||||
title: Micronaut项目集成
|
||||
sidebar_label: Micronaut项目集成
|
||||
---
|
||||
|
||||
Using Sureness to secure micronaut REST API by providing authentication(JWT,Basic,Digest) and authorization(RBAC)
|
||||
|
||||
|
||||
## What You Will Learn
|
||||
|
||||
* Creating a simple REST API using micronaut
|
||||
* Learn how to integrate Sureness into a micronaut application
|
||||
* Test API authentication - use JWT Auth, Basic Auth, Digest Auth to test the security of the REST API
|
||||
* Test API authorization - use different users to verify that they can access the REST API
|
||||
|
||||
|
||||
The tutorial assumes that you know what JWT, Basic Auth, Digest Auth, RBAC are. If you
|
||||
do not, then you can check [jwt](https://jwt.io/introduction/), [basic auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_basic.html) , [digest auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_digest.html), [rbac](https://en.wikipedia.org/wiki/Role-based_access_control) for an introduction.
|
||||
|
||||
## Setting Up Dependencies
|
||||
|
||||
First, you will need to create a maven project and add micronautn, Sureness dependencies coordinate
|
||||
|
||||
````
|
||||
|
||||
<properties>
|
||||
<release.version>8</release.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<packaging>jar</packaging>
|
||||
<jdk.version>1.8</jdk.version>
|
||||
<micronaut.version>2.4.3</micronaut.version>
|
||||
<micronaut-maven-plugin.version>1.1.8</micronaut-maven-plugin.version>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<exec.mainClass>com.usthe.sureness.micronaut.Application</exec.mainClass>
|
||||
<micronaut.runtime>netty</micronaut.runtime>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-bom</artifactId>
|
||||
<version>${micronaut.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.30</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.usthe.sureness</groupId>
|
||||
<artifactId>sureness-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-inject</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-validation</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut.test</groupId>
|
||||
<artifactId>micronaut-test-junit5</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-http-client</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-http-server-netty</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-runtime</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>io.micronaut.build</groupId>
|
||||
<artifactId>micronaut-maven-plugin</artifactId>
|
||||
<version>${micronaut-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<annotationProcessorPaths combine.children="append">
|
||||
<path>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-inject-java</artifactId>
|
||||
<version>${micronaut.version}</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>micronaut-validation</artifactId>
|
||||
<version>${micronaut.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<compilerArgs>
|
||||
<arg>-Amicronaut.processing.group=com.usthe.sureness</arg>
|
||||
<arg>-Amicronaut.processing.module=micronaut-sureness</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
|
||||
````
|
||||
|
||||
|
||||
- [User Guide](https://docs.micronaut.io/2.4.3/guide/index.html)
|
||||
- [API Reference](https://docs.micronaut.io/2.4.3/api/index.html)
|
||||
- [Configuration Reference](https://docs.micronaut.io/2.4.3/guide/configurationreference.html)
|
||||
- [Micronaut Guides](https://guides.micronaut.io/index.html)
|
||||
|
||||
We need to create a simple micronautn app and provide some REST API for test.
|
||||
|
||||
|
||||
|
||||
## Setting Up Sureness
|
||||
|
||||
#### 1.Run Micronaut Application
|
||||
|
||||
```
|
||||
|
||||
import io.micronaut.runtime.Micronaut;
|
||||
|
||||
|
||||
public class Application{
|
||||
|
||||
public static void main(String[] args) {
|
||||
Micronaut.run(Application.class, args);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### 2. Config Document Datasource - `sureness.yml`
|
||||
|
||||
Sureness authentication requires us to provide our own account data, role permission data. These data may come from document, databases,, annotations, etc. When we use sureness default configuration above, the datasource is document - `sureness.yml`.
|
||||
|
||||
Create a file named `sureness.yml` in the `resource` directory. Configure account data, role permission data in the `sureness.yml`. eg:
|
||||
|
||||
````yaml
|
||||
## -- sureness.yml document dataSource-- ##
|
||||
|
||||
# load api resource which need be protected, config role who can access these resource.
|
||||
# resources that are not configured are also authenticated and protected by default, but not authorized
|
||||
# eg: /api/v2/host===post===[role2,role3] means /api/v2/host===post can be access by role2,role3
|
||||
# eg: /api/v1/source2===get===[] means /api/v1/source2===get can not be access by any role
|
||||
resourceRole:
|
||||
- /api/v1/source1===get===[role2]
|
||||
- /api/v1/source1===post===[role1]
|
||||
- /api/v1/source1===delete===[role3]
|
||||
- /api/v1/source1===put===[role1,role2]
|
||||
- /api/v1/source2===get===[]
|
||||
- /api/v2/host===post===[role2,role3]
|
||||
- /api/v2/host===get===[role2,role3]
|
||||
- /api/v2/host===delete===[role2,role3]
|
||||
- /api/v2/host===put===[role2,role3]
|
||||
- /api/v3/*===*===[role1,role2,role3]
|
||||
|
||||
# load api resource which do not need be protected, means them need be excluded.
|
||||
# these api resource can be access by everyone
|
||||
excludedResource:
|
||||
- /api/v3/host===get
|
||||
- /**/*.html===get
|
||||
- /**/*.js===get
|
||||
- /**/*.css===get
|
||||
- /**/*.ico===get
|
||||
|
||||
# account info
|
||||
# there are three account: admin, root, tom
|
||||
# eg: admin has [role1,role2] ROLE, unencrypted password is admin, encrypted password is 0192023A7BBD73250516F069DF18B500
|
||||
# eg: root has role1, unencrypted password is 23456
|
||||
# eg: tom has role3, unencrypted password is 32113
|
||||
account:
|
||||
- appId: admin
|
||||
# if add salt, the password is encrypted password - the result: MD5(password+salt)
|
||||
# digest auth not support encrypted password
|
||||
# if no salt, the password is unencrypted password
|
||||
credential: 0192023A7BBD73250516F069DF18B500
|
||||
salt: 123
|
||||
role: [role1,role2]
|
||||
- appId: root
|
||||
credential: 23456
|
||||
role: [role1,role2]
|
||||
- appId: tom
|
||||
credential: 32113
|
||||
role: [role3]
|
||||
|
||||
````
|
||||
|
||||
|
||||
|
||||
#### 3. Add an Interceptor Intercepting All Requests
|
||||
|
||||
The essence of sureness is to intercept all rest requests for authenticating and authorizing. The interceptor can be a filter or interceptor, it intercepts all request to check them. In Micronaut, we use Filter
|
||||
```java
|
||||
@Filter("/**")
|
||||
public class MicronautSurenessFilterExample implements HttpServerFilter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MicronautSurenessFilterExample.class);
|
||||
|
||||
@Inject
|
||||
private SurenessSecurityManager securityManager ;
|
||||
|
||||
|
||||
@Override
|
||||
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request,
|
||||
ServerFilterChain chain) {
|
||||
Integer statusCode = null;
|
||||
String errorMsg = null;
|
||||
try {
|
||||
SubjectSum subject =securityManager.checkIn(request);
|
||||
if (subject != null) {
|
||||
SurenessContextHolder.bindSubject(subject);
|
||||
}
|
||||
} catch (ProcessorNotFoundException | UnknownAccountException | UnsupportedSubjectException e4) {
|
||||
logger.debug("this request is illegal");
|
||||
statusCode = HttpStatus.BAD_REQUEST.getCode();
|
||||
errorMsg = e4.getMessage();
|
||||
} catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
|
||||
logger.debug("the account is disabled");
|
||||
statusCode = HttpStatus.FORBIDDEN.getCode();
|
||||
errorMsg = e2.getMessage();
|
||||
} catch (IncorrectCredentialsException | ExpiredCredentialsException e3) {
|
||||
logger.debug("this account credential is incorrect or expired");
|
||||
statusCode = HttpStatus.FORBIDDEN.getCode();
|
||||
errorMsg = e3.getMessage();
|
||||
} catch (UnauthorizedException e5) {
|
||||
logger.debug("this account can not access this resource");
|
||||
statusCode = HttpStatus.FORBIDDEN.getCode();
|
||||
errorMsg = e5.getMessage();
|
||||
} catch (RuntimeException e) {
|
||||
logger.error("other exception happen: ", e);
|
||||
statusCode = HttpStatus.FORBIDDEN.getCode();
|
||||
errorMsg = e.getMessage();
|
||||
}
|
||||
if (statusCode != null && errorMsg != null) {
|
||||
String finalErrorMsg = errorMsg;
|
||||
Integer finalStatusCode = statusCode;
|
||||
logger.info(statusCode+"--->"+errorMsg);
|
||||
try {
|
||||
URI location = new URI("/auth/error");
|
||||
request = request.mutate().headers(httpHeaders -> {
|
||||
httpHeaders.add("statusCode", String.valueOf(finalStatusCode));
|
||||
httpHeaders.add("errorMsg", finalErrorMsg);
|
||||
}).uri(location);
|
||||
}catch (URISyntaxException e){
|
||||
logger.error("uri error");
|
||||
}
|
||||
}
|
||||
return chain.proceed(request);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return ServerFilterPhase.SECURITY.order();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
```
|
||||
SurenessSecurityManager configuration
|
||||
|
||||
```java
|
||||
import io.micronaut.context.annotation.Factory;
|
||||
|
||||
@Factory
|
||||
public class SurenessConfiguration {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SurenessConfiguration.class);
|
||||
|
||||
@Factory
|
||||
public SurenessSecurityManager init() {
|
||||
SurenessAccountProvider accountProvider = new DocumentAccountProvider();
|
||||
List<Processor> processorList = new LinkedList<>();
|
||||
NoneProcessor noneProcessor = new NoneProcessor();
|
||||
processorList.add(noneProcessor);
|
||||
PasswordProcessor passwordProcessor = new PasswordProcessor();
|
||||
passwordProcessor.setAccountProvider(accountProvider);
|
||||
processorList.add(passwordProcessor);
|
||||
DefaultProcessorManager processorManager = new DefaultProcessorManager(processorList);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("DefaultProcessorManager init");
|
||||
}
|
||||
PathTreeProvider pathTreeProvider = new DocumentPathTreeProvider();
|
||||
DefaultPathRoleMatcher pathRoleMatcher = new DefaultPathRoleMatcher();
|
||||
pathRoleMatcher.setPathTreeProvider(pathTreeProvider);
|
||||
pathRoleMatcher.buildTree();
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("DefaultPathRoleMatcher init");
|
||||
}
|
||||
|
||||
// SubjectFactory init
|
||||
SubjectFactory subjectFactory = new SurenessSubjectFactory();
|
||||
List<SubjectCreate> subjectCreates = Arrays.asList(
|
||||
new NoneSubjectReactiveCreator(),
|
||||
new BasicSubjectReactiveCreator());
|
||||
subjectFactory.registerSubjectCreator(subjectCreates);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("SurenessSubjectFactory init");
|
||||
}
|
||||
|
||||
// surenessSecurityManager init
|
||||
SurenessSecurityManager securityManager = SurenessSecurityManager.getInstance();
|
||||
securityManager.setPathRoleMatcher(pathRoleMatcher);
|
||||
securityManager.setSubjectFactory(subjectFactory);
|
||||
securityManager.setProcessorManager(processorManager);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("SurenessSecurityManager init");
|
||||
}
|
||||
return securityManager;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
#### 4. Last, Implement Auth Exception Handling Process
|
||||
|
||||
Sureness uses exception handling process:
|
||||
|
||||
- If auth success, method - `checkIn()` will return a `SubjectSum` object containing user information.
|
||||
- If auth failure, method - `checkIn()` will throw different types of auth exceptions.
|
||||
|
||||
We need to continue the subsequent process based on these exceptions.(eg: return the request response)
|
||||
|
||||
Here we need to customize the exceptions thrown by `checkIn`, passed directly when auth success, catch exception when auth failure and do something:
|
||||
|
||||
````
|
||||
// when auth error , add error msg to HttpRequest
|
||||
if (statusCode != null && errorMsg != null) {
|
||||
String finalErrorMsg = errorMsg;
|
||||
Integer finalStatusCode = statusCode;
|
||||
logger.info(statusCode+"--->"+errorMsg);
|
||||
try {
|
||||
URI location = new URI("/auth/error");
|
||||
request = request.mutate().headers(httpHeaders -> {
|
||||
httpHeaders.add("statusCode", String.valueOf(finalStatusCode));
|
||||
httpHeaders.add("errorMsg", finalErrorMsg);
|
||||
}).uri(location);
|
||||
}catch (URISyntaxException e){
|
||||
logger.error("uri error");
|
||||
}
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
|
||||
**All done, we can test now!**
|
||||
|
||||
## Test
|
||||
|
||||
Through the above steps, a complete auth function project is completed. Someone maybe think that with only these few steps, where is its complete function and what can it support?
|
||||
This built project is based on the RBAC permission model and supports Baisc authentication, Digest authentication and JWT authentication. It can fine-grained control the user's access to the restful api provided by the Javalin. That is to control which users can access which api.
|
||||
|
||||
Let's test it. (we use postman and chrome to test.)
|
||||
|
||||
### Test Authentication
|
||||
|
||||
#### 1. Basic Auth Test
|
||||
|
||||
Use postman Basic auth, as shown below:
|
||||
|
||||
* success - input username: admin, password: admin
|
||||
|
||||

|
||||
|
||||
|
||||
* fail - input username: admin, password: admin1234
|
||||
|
||||

|
||||
|
||||
|
||||
## Conclusion
|
||||
|
||||
micronaut is a framework dedicated to simplicity and ease of use, and so is Sureness.
|
||||
We hope you enjoy this tutorial. Of course, the tutorial only introduces a simple introduction. Our account data, role permission data can not only be written in `sureness.yml`, but also loaded and obtained from the database and annotations. We can also customize the authentication method, data source, etc.
|
||||
Finally, thank you again for reading.
|
||||
|
||||
[DEMO SOURCE CODE ON GITHUB](https://github.com/usthe/sureness/tree/master/samples/javalin-sureness)
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
id: sample-quarkus
|
||||
title: Quarkus项目集成
|
||||
sidebar_label: Quarkus项目集成
|
||||
---
|
||||
|
||||
[quarkus-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/quarkus-sureness)
|
||||
|
||||
- 基于`quarkus, jax-rs`
|
||||
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
|
||||
- 使用默认的`sureness-config`
|
||||
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
|
||||
- 例子中包含`REST API`
|
||||
- 保护入口: `SurenessFilterExample`
|
||||
- 推荐使用`postman`测试
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
id: sample-spring-webflux
|
||||
title: Spring-Webflux项目集成
|
||||
sidebar_label: Spring-Webflux项目集成
|
||||
---
|
||||
|
||||
[spring-webflux-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/spring-webflux-sureness)
|
||||
|
||||
- 基于`spring-webflux`
|
||||
- 自定义 `subject creator (BasicSubjectReactiveCreator, JwtSubjectReactiveCreator, NoneSubjectReactiveCreator)` 适配 `ServerHttpRequest` 请求体
|
||||
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
|
||||
- 使用默认的`JWT, Basic Auth`方式认证鉴权
|
||||
- 例子中包含`REST API`
|
||||
- 保护入口: `SurenessFilterExample`
|
||||
- 推荐使用`postman`测试
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
id: sample-tom
|
||||
title: Springboot项目集成-数据库方案
|
||||
sidebar_label: Springboot项目集成-数据库方案
|
||||
---
|
||||
|
||||
[Springboot项目集成-数据库方案代码仓库地址](https://github.com/tomsun28/sureness/tree/master/sample-tom)
|
||||
|
||||
- 基于`springboot,jpa...`
|
||||
- 自定义数据源,使用从数据库加载账户信息,资源角色,过滤资源等信息,这样便于动态调整(见`AccountProvider ResourceProvider`)
|
||||
- 除了使用了默认的`JWT, Basic Auth`方式认证鉴权,新增自定义认证鉴权(自定义`subject subjectCreator processor...`)
|
||||
- 推荐使用`postman`测试,测试样例为`sample-tom-postman.json`,导入`postman`即可
|
||||
|
||||
样例中包含2种自定义认证鉴权方式:
|
||||
|
||||
1. 自定义了一个单独的`subjectCreator` 见 `CustomPasswdSubjectCreator`
|
||||
演示功能就是自定义的从不同地方获取请求体的账户密码,来创建默认的`PasswordSubject`,走默认的账户密码认证流程
|
||||
|
||||
2. 自定义了一整套流程(包含`subject subjectCreator processor`) 见 `CustomTokenSubject CustomTokenSubjectCreator CustomTokenProcessor`
|
||||
演示功能就是自定义一个简单的`token`作为`subject`对象,对其自定义创建获取方式-`creator`和自定义认证鉴权处理流程-`processor`.
|
||||
此自定义流程也演示了一个简单的`token`刷新流程
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: introduce
|
||||
title: Sureness 介绍
|
||||
sidebar_label: 介绍
|
||||
slug: /
|
||||
---
|
||||
|
||||
> 面向`REST API`的高性能认证鉴权框架
|
||||
|
||||
[](https://www.apache.org/licenses/LICENSE-2.0.html)
|
||||
[](https://search.maven.org/artifact/com.usthe.sureness/sureness-core)
|
||||

|
||||
[](https://gitter.im/usthe/sureness)
|
||||

|
||||
[](https://gitee.com/dromara/sureness/stargazers)
|
||||
[](https://github.com/dromara/sureness)
|
||||
|
||||
|
||||
## 📫 背景
|
||||
|
||||
在主流的前后端分离架构中,如何通过有效快速的认证鉴权来保护后端提供的`REST API`变得尤为重要。对现存框架,不原生支持`RESTful`的`Apache Shiro`,
|
||||
还是深度绑定`Spring`的`Spring Security`,或多或少都不是我们的理想型。
|
||||
于是乎`Sureness`诞生了,我们希望能解决这些,提供一个面向**REST API**,**无框架依赖**,可以**动态修改权限**,**多认证策略**,**更快速度**,**易用易扩展**的认证鉴权框架。
|
||||
|
||||
## 🎡 <font color="green">介绍</font>
|
||||
|
||||
> [Sureness](https://github.com/dromara/sureness) 是我们在深度使用 `Apache Shiro` 之后,吸取其优点全新设计开发的一个认证鉴权框架
|
||||
> 面向 `REST API` 的认证鉴权,基于 `RBAC` (用户-角色-资源)主要关注于对 `API` 的安全保护
|
||||
> 无特定Web框架依赖(已有 `Spring Boot,Quarkus,Javalin,Ktor,Micronaut,Jfinal,Solon` 等集成样例)
|
||||
> 支持动态修改权限配置(动态修改配置每个 `API` 谁有权访问)
|
||||
> 支持 `Websocket` ,主流 `HTTP` 容器 `Servlet` 和 `JAX-RS`
|
||||
> 支持多种认证策略, `JWT, Basic Auth, Digest Auth` ... 可扩展自定义认证方式
|
||||
> 基于改进的字典匹配树拥有的高性能
|
||||
> 良好的扩展接口, 样例和文档助急速理解扩展使用
|
||||
|
||||
> `Sureness`的低配置,易扩展,不耦合其他框架,希望能对系统多场景快速安全的保护
|
||||
|
||||
##### 🔍 对比
|
||||
|
||||
| ~ | Sureness | Shiro | Spring Security |
|
||||
| --- | --- | --- | --- |
|
||||
| **多框架支持** | 支持 | 需改动支持 | 不支持 |
|
||||
| **REST API** | 支持 | 需改动支持 | 支持 |
|
||||
| **Websocket** | 支持 | 不支持 | 不支持 |
|
||||
| **过滤链匹配** | 优化的字典匹配树 | ant匹配 | ant匹配 |
|
||||
| **注解支持** | 支持 | 支持 | 支持 |
|
||||
| **Servlet** | 支持 | 支持 | 支持|
|
||||
| **JAX-RS** | 支持 | 不支持 | 不支持|
|
||||
| **权限动态修改** | 支持 | 需改动支持 | 需改动支持|
|
||||
| **性能速度** | 较快 | 较慢 | 较慢|
|
||||
| **学习曲线** | 简单 | 简单 | 陡峭|
|
||||
|
||||
##### 📈 基准性能测试
|
||||
|
||||

|
||||
|
||||
**基准测试显示Sureness对比无权限框架应用损耗0.026ms性能,Shiro损耗0.088ms,Spring Security损耗0.116ms,
|
||||
相比之下Sureness性能(参考TPS损耗)是Shiro的3倍,Spring Security的4倍**
|
||||
**性能差距会随着api匹配链的增加而进一步拉大**
|
||||
详见[基准测试](https://github.com/tomsun28/sureness-shiro-spring-security)
|
||||
|
||||
|
||||
##### ✌ 框架支持样例
|
||||
|
||||
- [x] Sureness集成**Spring Boot**样例(配置文件方案) [sample-bootstrap](/docs/integrate/sample-bootstrap)
|
||||
- [x] Sureness集成**Spring Boot**样例(数据库方案) [sample-tom](/docs/integrate/sample-tom)
|
||||
- [x] Sureness集成**Quarkus**样例 [sample-quarkus](/docs/integrate/sample-quarkus)
|
||||
- [x] Sureness集成**Javalin**样例 [sample-javalin](/docs/integrate/sample-javalin)
|
||||
- [x] Sureness集成**Ktor**样例 [sample-ktor](/docs/integrate/sample-ktor)
|
||||
- [x] Sureness集成**Spring Webflux**样例 [spring-webflux-sureness](/docs/integrate/sample-spring-webflux)
|
||||
- [x] Sureness集成**Micronaut**样例 [sample-micronaut](/docs/integrate/sample-micronaut)
|
||||
- [x] Sureness使用Session样例 [sureness-session](https://github.com/usthe/sureness/tree/master/samples/sureness-session)
|
||||
- [x] Sureness分布式缓存Session样例 [sureness-redis-session](https://github.com/usthe/sureness/tree/master/samples/sureness-redis-session)
|
||||
- [x] More samples todo
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
id: sponsor
|
||||
title: 赞助
|
||||
sidebar_label: 赞助
|
||||
---
|
||||
|
||||
|
||||
**sureness对个人或企业完全免费,如果您喜欢这个项目并且愿意提供帮助,请作者喝杯咖啡吧**
|
||||
|
||||
### 微信支付宝
|
||||
|
||||

|
||||
|
||||
|
||||
### paypal
|
||||
|
||||
[https://paypal.me/tomsun28](https://paypal.me/tomsun28)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
id: annotation-datasource
|
||||
title: 注解形式的资源权限数据源
|
||||
sidebar_label: 注解权限数据源
|
||||
---
|
||||
|
||||
`sureness`认证鉴权,当然也需要我们提供自己的账户数据,角色权限数据等,这些数据可能来自文本,关系数据库,非关系数据库,注解等。
|
||||
我们提供了数据源接口:`SurenessAccountProvider` - 账户数据接口, `PathTreeProvider` - 资源权限数据接口,用户可以实现此接口实现自定义数据源。
|
||||
|
||||
`sureness`实现注解权限的方式不是调用方法前aop判断,而是启动时扫描注解里的数据作为权限数据源来使用,这样方便了流程统一和框架无关性。
|
||||
这里介绍下注解形式的权限数据源配置方法。
|
||||
|
||||
1. 首先我们需要在sureness启动配置中配置使用注解数据源作为权限数据源。
|
||||
|
||||
```
|
||||
@Bean
|
||||
TreePathRoleMatcher pathRoleMatcher() {
|
||||
// 实例化资源权限路径匹配者,其会根据请求的路径和已有的资源权限数据匹配出所需的角色信息
|
||||
DefaultPathRoleMatcher pathRoleMatcher = new DefaultPathRoleMatcher();
|
||||
// 实例化注解形式的资源权限数据加载者AnnotationLoader,其实现了PathTreeProvider接口
|
||||
AnnotationPathTreeProvider pathTreeProvider = new AnnotationPathTreeProvider();
|
||||
// 设置AnnotationLoader要扫描的包路径,其会扫描包路径下所有类方法上的@RequiresRoles, @WithoutAuth 注解获取数据
|
||||
pathTreeProvider.setScanPackages(Arrays.asList("com.usthe.sureness.sample.tom.controller"));
|
||||
// 将AnnotationLoader数据源设置为sureness的权限资源数据源
|
||||
pathRoleMatcher.addPathTreeProvider(pathTreeProvider);
|
||||
pathRoleMatcher.buildTree();
|
||||
return pathRoleMatcher;
|
||||
}
|
||||
```
|
||||
|
||||
2. 在提供的接口方法中使用注解,注解使用格式:
|
||||
```
|
||||
@RequiresRoles(roles = {"role1", "role2"}, mapping = "/resource", method = "post")
|
||||
其表示资源 /resource===post 的需要角色 role1或者role2才能访问
|
||||
```
|
||||
```
|
||||
@WithoutAuth(mapping = "/resource/*", method = "put")
|
||||
其表示资源 /resource/*===put 的可以被任何请求访问
|
||||
```
|
||||
|
||||
3. 建议。
|
||||
注解形式的权限数据源虽然比较方便我们开发,但其写死在代码中,无法动态修改权限角色配置数据,对于大型项目反而不是很适用。
|
||||
`sureness`提供了多个数据源同时加载的功能,即我们可以同时将注解形式的权限数据源和数据库里的配置数据作为数据源,加载到sureness配置中,
|
||||
对于不常修改的权限配置,我们可以将其配置到注解,对于其他需要动态修改的权限数据,我们就将其配置到数据库中。
|
||||
|
||||
|
||||
当然也我们提供了默认文本数据源,默认文本数据源具体实现,请参考 [默认文本数据源](/docs/start/default-datasource)
|
||||
数据源也可以来自数据库等存储,我们提供了接口让用户轻松的自定义数据源,详见[自定义数据源](/docs/advanced/custom-datasource)
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
id: default-auth
|
||||
title: 默认支持的认证方式
|
||||
sidebar_label: 默认认证方式
|
||||
---
|
||||
|
||||
`sureness`目前默认支持的认证方式有`bearer jwt`,`basic auth`, `digest auth`, 当然用户可以通过扩展`Processor`,`Subject`和`SubjectCreate`接口实现自定义的认证方式
|
||||
|
||||
#### `bearer jwt`
|
||||
`jwt`即`json web token`,是目前很流行的跨域,无状态,安全认证解决方案,介绍详见[网络](http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html)
|
||||
我们这里为啥叫`bearer jwt`是因为`jwt`是放入到http请求头的`bearer token`里面,即: `Authorization: Bearer jsonWebTokenValue`
|
||||
eg:
|
||||
```
|
||||
GET /api/v1/source1 HTTP/1.1
|
||||
Host: localhost:8088
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer eyJhbGciOiJIUzUxMiIsInppcCI6IkRFRiJ9.eNocjEEOwiAQRe8y65IwCBQ4hlvjotAhVqs1DBoT492l7F5e_vtfuNYFAliUPs3aCrIuCW1nFDHlUaBVqJOLJpkIA_ArtnHd7o0X5s43egim8qayy6lCQOOUd15JHIA-zy4OUo5dlG2lFp46KDjvR0fKhfgCIU8r0-8PAAD__w.f-3klWWDpEO3uDLlx2S53DV2cYernwVEDwcC6z1JexocbZoxRKmASTOuky1qMCxy_hV8-RbuMjDmI3ASa_FQOw
|
||||
```
|
||||
|
||||
我们可以在`postman`如下使用它: 将`jwt`值塞入`Bearer Token`里.
|
||||

|
||||
|
||||
#### `basic auth`
|
||||
`basic auth`即`Basic access authentication`,经典的`http`基本认证方式,介绍详见[网络](https://www.jianshu.com/p/4cd42f7359f4)
|
||||
这种认证方式是将账户密码组成的字符串`base64`加密,放入到请求头的 `Authorization`中, 即:`Authorization: Basic base64encode(username+":"+password)`
|
||||
eg:
|
||||
```
|
||||
GET /api/v1/source1 HTTP/1.1
|
||||
Host: localhost:8088
|
||||
Content-Type: application/json
|
||||
Authorization: Basic dG9tOjMyMTEz
|
||||
```
|
||||
|
||||
我们可以在`postman`如下使用它: 在`Basic Auth`类型的`Authorization`中输入账户密码即可,`postman`会自动对其`base64`加密.
|
||||

|
||||
|
||||
#### `digest auth`
|
||||
`digest auth`即`Digest access authentication`,经典的`http`摘要认证方式,用于保护传输的密码,介绍详见[网络](https://www.cnblogs.com/xiaoxiaotank/p/11078571.html)
|
||||
下面是`digest auth`的认证流程(图片来源于[网络](https://www.cnblogs.com/xiaoxiaotank/p/11078571.html)):
|
||||

|
||||
|
||||
我们可以在`chrome`浏览器直接使用它: 访问`url`,在弹出的对话框中输入账户密码即可,`chrome`浏览器会自动进行认证流程.
|
||||

|
||||
|
||||
|
||||
#### 其他认证方式
|
||||
目前`sureness`默认支持这三种主流的认证方式,满足绝大部分需求,当然你也可以很轻松的自定义认证方式,详见[自定义Subject](/docs/advanced/custom-subject)
|
||||
|
||||
我们提供了默认认证方式的使用`DEMO`,请参考 [一步一步搭建认证鉴权系统](/docs/integrate/sample-bootstrap)
|
||||
当然我们也提供了自定义认证方式的扩展`DEMO`,请参考 [Springboot项目集成-数据库方案](/docs/integrate/sample-tom)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: default-datasource
|
||||
title: 默认文本配置数据源
|
||||
sidebar_label: 默认文本数据源
|
||||
---
|
||||
|
||||
`sureness`认证鉴权当然也需要我们自己的配置数据:账户数据,角色权限数据等
|
||||
这些配置数据可能来自文本,关系数据库,非关系数据库
|
||||
我们提供了配置数据接口`SurenessAccountProvider`, `PathTreeProvider`, 用户可以实现此接口实现自定义配置数据源
|
||||
|
||||
当然我们也提供默认文本形式的配置数据实现 `DocumentResourceDefaultProvider`
|
||||
用户可以创建文件`sureness.yml`来配置数据,配置样例如下:
|
||||
|
||||
```
|
||||
## -- sureness.yml文本数据源 -- ##
|
||||
|
||||
# 加载到匹配字典的资源,也就是需要被保护的,设置了所支持角色访问的资源
|
||||
# 没有配置的资源也默认被认证保护,但不鉴权
|
||||
# eg: /api/v1/source1===get===[role2] 表示 /api/v2/host===post 这条资源支持 role2 这一种角色访问
|
||||
# eg: /api/v1/source2===get===[] 表示 /api/v1/source2===get 这条资源不支持任何角色访问
|
||||
resourceRole:
|
||||
- /api/v1/source1===get===[role2]
|
||||
- /api/v1/source1===delete===[role3]
|
||||
- /api/v1/source1===put===[role1,role2]
|
||||
- /api/v1/source2===get===[]
|
||||
- /api/v1/source2/*/*===get===[role2]
|
||||
- /api/v2/source3/*===get===[role2]
|
||||
- /api/v3/source===*===[role2]
|
||||
|
||||
# 需要被过滤保护的资源,不认证鉴权直接访问
|
||||
# /api/v1/source3===get 表示 /api/v1/source3===get 可以被任何人访问 无需登录认证鉴权
|
||||
excludedResource:
|
||||
- /api/v1/account/auth===post
|
||||
- /api/v1/source3===get
|
||||
- /**/*.html===get
|
||||
- /**/*.js===get
|
||||
- /**/*.css===get
|
||||
- /**/*.ico===get
|
||||
- /**/*.png===*
|
||||
|
||||
# 用户账户信息
|
||||
# 下面有 admin root tom三个账户
|
||||
# eg: admin 拥有[role1,role2]角色,明文密码为admin,加盐密码为0192023A7BBD73250516F069DF18B500
|
||||
# eg: root 拥有[role1],密码为明文23456
|
||||
# eg: tom 拥有[role3],密码为明文32113
|
||||
account:
|
||||
- appId: admin
|
||||
# 如果填写了加密盐--salt,则credential为MD5(password+salt)的32位结果
|
||||
# 没有盐认为不加密,credential为明文
|
||||
# 若对密码加盐 则不支持digest认证
|
||||
credential: 0192023A7BBD73250516F069DF18B500
|
||||
salt: 123
|
||||
role: [role1,role2]
|
||||
- appId: root
|
||||
credential: 23456
|
||||
role: [role1]
|
||||
- appId: tom
|
||||
credential: 32113
|
||||
role: [role3]
|
||||
|
||||
```
|
||||
|
||||
我们提供了默认文本数据源使用`DEMO`,默认文本数据源具体实现,请参考 [一步一步搭建认证鉴权系统](/docs/integrate/sample-bootstrap)
|
||||
当然数据源也可以来自数据库等存储,我们提供了接口让用户轻松的自定义数据源,详见[自定义数据源](/docs/advanced/custom-datasource)
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
id: default-exception
|
||||
title: sureness 默认认证鉴权异常
|
||||
sidebar_label: 默认异常类型
|
||||
---
|
||||
|
||||
`sureness`使用异常处理流程:
|
||||
1. 若认证鉴权成功,`checkIn`会返回包含用户信息的`SubjectSum`对象
|
||||
2. 若中间认证鉴权失败,`checkIn`会抛出不同类型的认证鉴权异常,用户需根据这些异常来继续后面的流程(返回相应的请求响应)
|
||||
|
||||
这里我们就需要对`checkIn`抛出的异常做自定义处理,认证鉴权成功直接通过,失败抛出特定异常进行处理,如下:
|
||||
|
||||
```
|
||||
try {
|
||||
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(servletRequest);
|
||||
} catch (ProcessorNotFoundException | UnknownAccountException | UnsupportedSubjectException e4) {
|
||||
// 账户创建相关异常
|
||||
} catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
|
||||
// 账户禁用相关异常
|
||||
} catch (IncorrectCredentialsException | ExpiredCredentialsException e3) {
|
||||
// 认证失败相关异常
|
||||
} catch (UnauthorizedException e5) {
|
||||
// 鉴权失败相关异常
|
||||
} catch (RuntimeException e) {
|
||||
// 其他自定义异常
|
||||
}
|
||||
```
|
||||
|
||||
sureness 默认支持的异常处理流程中的异常如下:
|
||||
|
||||
`sureness`异常 | 异常描述
|
||||
--- | ---
|
||||
SurenessAuthenticationException | 基础认证异常,认证相关的子异常应该继承此异常
|
||||
SurenessAuthorizationException | 基础鉴权异常,鉴权相关的子异常应该继承此异常
|
||||
ProcessorNotFoundException | 认证异常,未找到支持此subject的processor
|
||||
UnknownAccountException | 认证异常,不存在此账户
|
||||
UnSupportedSubjectException | 认证异常,不支持的请求,未创建出subject
|
||||
DisabledAccountException | 认证异常,账户禁用
|
||||
ExcessiveAttemptsException | 认证异常,账户尝试认证次数过多
|
||||
IncrrectCredentialsException | 认证异常,密钥错误
|
||||
ExpiredCredentialsException | 认证异常,密钥认证过期
|
||||
NeedDigestInfoException | 认证异常, 通过getAuthenticate()返回客户端digest认证所需信息
|
||||
UnauthorizedException | 鉴权异常,没有权限访问此资源
|
||||
|
||||
自定义异常需要继承`SurenessAuthenticationException`或`SurenessAuthorizationException`才能被最外层捕获
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
id: path-match
|
||||
title: URI路径匹配
|
||||
sidebar_label: URI路径匹配
|
||||
---
|
||||
|
||||
我们配置的资源格式为:`requestUri===httpMethod`, 即请求的路径加上其请求方式(`post,get,put,delete...或者*,*匹配所有请求方式`)作为一个整体被视作一个资源
|
||||
`eg: /api/v2/book===get` `get`方式请求`/api/v2/book`接口数据
|
||||
这里的`requestUri`支持url路径匹配符匹配: `str*str`, `*`, `**`
|
||||
|
||||
| 通配符 | 描述 |
|
||||
| --- | --- |
|
||||
| `str*str` | 字符串中的*匹配0个或者多个任意字符 |
|
||||
| `*` | 匹配0个或1个目录 |
|
||||
| `**` | 匹配0个或多个目录 |
|
||||
|
||||
|
||||
| 样例 | 说明 |
|
||||
| --- | --- |
|
||||
| `*.html` | 可以匹配 `content.html`, `user-ui.html` 等 |
|
||||
| `/api/*/book` | 可以匹配 `/api/user/book` 或 `/api/book` 等 |
|
||||
| `/**` | 可以匹配任何路径 |
|
||||
| `/**/foo` | 可以匹配 `/api/user/book/foo` 等 |
|
||||
|
||||
匹配优先级: 原始字符串 > `str*str` > `*` > `**`
|
||||
最长路径匹配原则:
|
||||
eg: `requestUri` 为`/app/book/foo`,若存在两个路径匹配模式`/app/**`和`/app/book/*`,则会匹配到`/app/book/*`
|
||||
@@ -0,0 +1,93 @@
|
||||
---
|
||||
id: quickstart
|
||||
title: 快速开始
|
||||
sidebar_label: 快速开始
|
||||
---
|
||||
|
||||
#### 🐕 使用前一些约定
|
||||
|
||||
- `Sureness`基于`RBAC`,即用户-角色-资源: 用户所属角色--角色拥有资源(API)--用户就能访问资源(API)
|
||||
- 我们将`REST API`请求视作一个资源,资源格式为: `requestUri===httpMethod`
|
||||
即请求的路径加上其请求方式(`post,get,put,delete...`)作为一个整体被视作资源来赋权配置
|
||||
`eg: /api/v2/book===get` `get`方式请求`/api/v2/book`接口数据
|
||||
|
||||
资源路径匹配详见 [url路径匹配](/docs/start/path-match)
|
||||
|
||||
#### 项目中加入Sureness
|
||||
|
||||
项目使用`maven`或`gradle`构建,加入坐标
|
||||
```
|
||||
<dependency>
|
||||
<groupId>com.usthe.sureness</groupId>
|
||||
<artifactId>sureness-core</artifactId>
|
||||
<version>1.0.6</version>
|
||||
</dependency>
|
||||
```
|
||||
```
|
||||
compile group: 'com.usthe.sureness', name: 'sureness-core', version: '1.0.6'
|
||||
```
|
||||
|
||||
#### 🐵 使用默认配置来配置Sureness
|
||||
默认配置使用了文件数据源`sureness.yml`作为账户权限数据源
|
||||
默认配置支持了`JWT, Basic auth, Digest auth`认证
|
||||
```
|
||||
@Bean
|
||||
public DefaultSurenessConfig surenessConfig() {
|
||||
return new DefaultSurenessConfig();
|
||||
}
|
||||
```
|
||||
|
||||
#### 配置权限账户数据源
|
||||
|
||||
`Sureness`认证鉴权,当然也需要我们提供自己的账户数据,角色权限数据等,这些数据可能来自文本,关系数据库,非关系数据库,注解等。
|
||||
我们提供了数据源接口:`SurenessAccountProvider`, `PathTreeProvider`,用户可以实现此接口实现自定义数据源。
|
||||
|
||||
当前我们也提供文本形式的数据源实现 `DocumentResourceDefaultProvider` 和 注解形式的资源权限数据源实现 `AnnotationLoader`。
|
||||
如果是使用了[默认sureness配置-DefaultSurenessConfig](#使用默认配置来配置sureness),其配置的是文本数据源,用户可以直接通过修改`sureness.yml`文件来配置数据。
|
||||
|
||||
文本数据源`sureness.yml`配置使用方式详见文档 [默认文本数据源](/docs/start/default-datasource)
|
||||
注解形式的资源权限数据源配置使用方式详见文档 [注解资源权限数据源](/docs/start/annotation-datasource)
|
||||
|
||||
我们提供了使用代码`DEMO`:
|
||||
默认文本数据源具体实现,请参考[Sureness集成Spring Boot样例(配置文件方案)--sample-bootstrap](https://github.com/tomsun28/sureness/tree/master/sample-bootstrap)
|
||||
若权限配置数据来自数据库,请参考[Sureness集成Spring Boot样例(数据库方案)--sample-tom](https://github.com/tomsun28/sureness/tree/master/sample-tom)
|
||||
|
||||
#### 添加过滤器拦截所有请求
|
||||
|
||||
`Sureness`的本质就拦截所有`API`请求对其认证鉴权判断。
|
||||
入口拦截器器实现一般可以是 `filter or spring interceptor`
|
||||
在拦截器中加入`Sureness`的安全过滤器,如下:
|
||||
|
||||
```
|
||||
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(servletRequest)
|
||||
```
|
||||
|
||||
#### 实现认证鉴权相关异常处理流程
|
||||
|
||||
`Sureness`使用异常处理流程:
|
||||
1. 若认证鉴权成功,`checkIn`会返回包含用户信息的`SubjectSum`对象
|
||||
2. 若中间认证鉴权失败,`checkIn`会抛出不同类型的认证鉴权异常,用户需根据这些异常来继续后面的流程(返回相应的请求响应)
|
||||
|
||||
这里我们就需要对`checkIn`抛出的异常做自定义处理,认证鉴权成功直接通过,失败抛出特定异常进行处理,如下:
|
||||
|
||||
```
|
||||
try {
|
||||
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(servletRequest);
|
||||
} catch (ProcessorNotFoundException | UnknownAccountException | UnsupportedSubjectException e4) {
|
||||
// 账户创建相关异常
|
||||
} catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
|
||||
// 账户禁用相关异常
|
||||
} catch (IncorrectCredentialsException | ExpiredCredentialsException e3) {
|
||||
// 认证失败相关异常
|
||||
} catch (UnauthorizedException e5) {
|
||||
// 鉴权失败相关异常
|
||||
} catch (SurenessAuthenticationException | SurenessAuthorizationException e) {
|
||||
// 其他自定义异常
|
||||
}
|
||||
```
|
||||
|
||||
异常详见 [默认异常类型](/docs/start/default-exception)
|
||||
|
||||
**HAVE FUN**
|
||||
|
||||
> 如果这个[快速开始]对您不是很友好,可以参考下面一篇[一步一步搭建](https://juejin.cn/post/6921262609731682318),里面一步一步详细介绍了使用Sureness搭建一个完整功能认证鉴权项目的步骤。
|
||||
@@ -0,0 +1,432 @@
|
||||
---
|
||||
id: quickstart
|
||||
title: 一步一步搭建
|
||||
sidebar_label: 一步一步搭建
|
||||
---
|
||||
|
||||
下面我们来一步一步基于springboot,sureness搭建一个如下功能的认证鉴权系统。
|
||||
|
||||
1. 使用了配置文件来作为系统的账户数据和权限数据的数据源。
|
||||
2. 系统基于rbac权限模型,支持basic认证,digest认证,jwt认证。
|
||||
3. 能细粒度的控制用户对系统提供的restful api的访问权限,即哪些用户能访问哪些api。
|
||||
|
||||
多说无益,快速开始!
|
||||
|
||||
这里为了照顾到刚入门的同学,图文展示了每一步操作。有基础可直接略过。
|
||||
|
||||
### 初始化一个springboot web工程
|
||||
|
||||
在IDEA如下操作:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
### 提供一些模拟的restful api
|
||||
|
||||
新建一个controller, 在里面实现一些简单的restful api供外部测试调用
|
||||
|
||||
````
|
||||
/**
|
||||
* simulate api controller, for testing
|
||||
* @author tomsun28
|
||||
* @date 17:35 2019-05-12
|
||||
*/
|
||||
@RestController
|
||||
public class SimulateController {
|
||||
|
||||
/** access success message **/
|
||||
public static final String SUCCESS_ACCESS_RESOURCE = "access this resource success";
|
||||
|
||||
@GetMapping("/api/v1/source1")
|
||||
public ResponseEntity<String> api1Mock1() {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@PutMapping("/api/v1/source1")
|
||||
public ResponseEntity<String> api1Mock3() {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/v1/source1")
|
||||
public ResponseEntity<String> api1Mock4() {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@GetMapping("/api/v1/source2")
|
||||
public ResponseEntity<String> api1Mock5() {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@GetMapping("/api/v1/source2/{var1}/{var2}")
|
||||
public ResponseEntity<String> api1Mock6(@PathVariable String var1, @PathVariable Integer var2 ) {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@PostMapping("/api/v2/source3/{var1}")
|
||||
public ResponseEntity<String> api1Mock7(@PathVariable String var1) {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@GetMapping("/api/v1/source3")
|
||||
public ResponseEntity<String> api1Mock11(HttpServletRequest request) {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
@GetMapping("/api/v2/source2")
|
||||
public ResponseEntity<String> api1Mock12() {
|
||||
return ResponseEntity.ok(SUCCESS_ACCESS_RESOURCE);
|
||||
}
|
||||
|
||||
}
|
||||
````
|
||||
|
||||
### 项目中加入sureness依赖
|
||||
|
||||
在项目的pom.xml加入sureness的maven依赖坐标
|
||||
```
|
||||
<dependency>
|
||||
<groupId>com.usthe.sureness</groupId>
|
||||
<artifactId>sureness-core</artifactId>
|
||||
<version>1.0.3</version>
|
||||
</dependency>
|
||||
```
|
||||
如下:
|
||||
|
||||

|
||||
|
||||
|
||||
### 使用默认配置来配置sureness
|
||||
|
||||
新建一个配置类,创建对应的sureness默认配置bean
|
||||
sureness默认配置使用了文件数据源`sureness.yml`作为账户权限数据源
|
||||
默认配置支持了`jwt, basic auth, digest auth`认证
|
||||
```
|
||||
@Configuration
|
||||
public class SurenessConfiguration {
|
||||
|
||||
/**
|
||||
* sureness default config bean
|
||||
* @return default config bean
|
||||
*/
|
||||
@Bean
|
||||
public DefaultSurenessConfig surenessConfig() {
|
||||
return new DefaultSurenessConfig();
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 配置默认文本配置数据源
|
||||
|
||||
认证鉴权当然也需要我们自己的配置数据:账户数据,角色权限数据等
|
||||
这些配置数据可能来自文本,关系数据库,非关系数据库
|
||||
我们这里使用默认的文本形式配置 - sureness.yml, 在resource资源目录下创建sureness.yml文件
|
||||
在sureness.yml文件里配置我们的角色权限数据和账户数据,如下:
|
||||
|
||||
````
|
||||
## -- sureness.yml文本数据源 -- ##
|
||||
|
||||
# 加载到匹配字典的资源,也就是需要被保护的,设置了所支持角色访问的资源
|
||||
# 没有配置的资源也默认被认证保护,但不鉴权,例如/api/v1/source2===get
|
||||
# eg: /api/v1/source1===get===[role2] 表示 /api/v1/source1===get 这条资源支持 role2这一种角色访问
|
||||
# eg: /api/v2/source2===get===[] 表示 /api/v1/source2===get 这条资源不支持任何角色访问
|
||||
resourceRole:
|
||||
- /api/v1/source1===get===[role2]
|
||||
- /api/v1/source1===delete===[role3]
|
||||
- /api/v1/source1===put===[role1,role2]
|
||||
- /api/v2/source2===get===[]
|
||||
- /api/v1/source2/*/*===get===[role2]
|
||||
- /api/v2/source3/*===get===[role2]
|
||||
|
||||
# 需要被过滤保护的资源,不认证鉴权直接访问
|
||||
# /api/v1/source3===get 表示 /api/v1/source3===get 可以被任何人访问 无需登录认证鉴权
|
||||
excludedResource:
|
||||
- /api/v1/account/auth===post
|
||||
- /api/v1/source3===get
|
||||
- /**/*.html===get
|
||||
- /**/*.js===get
|
||||
- /**/*.css===get
|
||||
- /**/*.ico===get
|
||||
|
||||
# 用户账户信息
|
||||
# 下面有 admin root tom三个账户
|
||||
# eg: admin 拥有[role1,role2]角色,明文密码为admin,加盐密码为0192023A7BBD73250516F069DF18B500
|
||||
# eg: root 拥有[role1],密码为明文23456
|
||||
# eg: tom 拥有[role3],密码为明文32113
|
||||
account:
|
||||
- appId: admin
|
||||
# 如果填写了加密盐--salt,则credential为MD5(password+salt)的32位结果
|
||||
# 没有盐认为不加密,credential为明文
|
||||
# 若密码加盐 则digest认证不支持
|
||||
credential: 0192023A7BBD73250516F069DF18B500
|
||||
salt: 123
|
||||
role: [role1,role2]
|
||||
- appId: root
|
||||
credential: 23456
|
||||
role: [role1]
|
||||
- appId: tom
|
||||
credential: 32113
|
||||
role: [role3]
|
||||
|
||||
````
|
||||
|
||||
### 添加过滤器拦截所有请求,对所有请求进行认证鉴权
|
||||
|
||||
新建一个filter, 拦截所有请求,用sureness对所有请求进行认证鉴权。认证鉴权失败的请求sureness会抛出对应的异常,我们捕获响应的异常进行处理返回response即可。
|
||||
|
||||
````
|
||||
@Order(1)
|
||||
@WebFilter(filterName = "SurenessFilterExample", urlPatterns = "/*", asyncSupported = true)
|
||||
public class SurenessFilterExample implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) {}
|
||||
|
||||
@Override
|
||||
public void destroy() {}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
|
||||
throws IOException, ServletException {
|
||||
|
||||
try {
|
||||
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(servletRequest);
|
||||
// 认证鉴权成功则会返回带用户信息的subject 可以将subject信息绑定到当前线程上下文holder供后面使用
|
||||
if (subject != null) {
|
||||
SurenessContextHolder.bindSubject(subject);
|
||||
}
|
||||
} catch (ProcessorNotFoundException | UnknownAccountException | UnsupportedSubjectException e4) {
|
||||
// 账户创建相关异常
|
||||
responseWrite(ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST).body(e4.getMessage()), servletResponse);
|
||||
return;
|
||||
} catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
|
||||
// 账户禁用相关异常
|
||||
responseWrite(ResponseEntity
|
||||
.status(HttpStatus.UNAUTHORIZED).body(e2.getMessage()), servletResponse);
|
||||
return;
|
||||
} catch (IncorrectCredentialsException | ExpiredCredentialsException e3) {
|
||||
// 认证失败相关异常
|
||||
responseWrite(ResponseEntity
|
||||
.status(HttpStatus.UNAUTHORIZED).body(e3.getMessage()), servletResponse);
|
||||
return;
|
||||
} catch (NeedDigestInfoException e5) {
|
||||
// digest认证需要重试异常
|
||||
responseWrite(ResponseEntity
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.header("WWW-Authenticate", e5.getAuthenticate()).build(), servletResponse);
|
||||
return;
|
||||
} catch (UnauthorizedException e6) {
|
||||
// 鉴权失败相关异常,即无权访问此api
|
||||
responseWrite(ResponseEntity
|
||||
.status(HttpStatus.FORBIDDEN).body(e6.getMessage()), servletResponse);
|
||||
return;
|
||||
} catch (RuntimeException e) {
|
||||
// 其他异常
|
||||
responseWrite(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(),
|
||||
servletResponse);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 若未抛出异常 则认证鉴权成功 继续下面请求流程
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
} finally {
|
||||
SurenessContextHolder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* write response json data
|
||||
* @param content content
|
||||
* @param response response
|
||||
*/
|
||||
private static void responseWrite(ResponseEntity content, ServletResponse response) {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json;charset=utf-8");
|
||||
((HttpServletResponse)response).setStatus(content.getStatusCodeValue());
|
||||
content.getHeaders().forEach((key, value) ->
|
||||
((HttpServletResponse) response).addHeader(key, value.get(0)));
|
||||
try (PrintWriter printWriter = response.getWriter()) {
|
||||
if (content.getBody() != null) {
|
||||
if (content.getBody() instanceof String) {
|
||||
printWriter.write(content.getBody().toString());
|
||||
} else {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
printWriter.write(objectMapper.writeValueAsString(content.getBody()));
|
||||
}
|
||||
} else {
|
||||
printWriter.flush();
|
||||
}
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
像上面一样,
|
||||
1. 若认证鉴权成功,`checkIn`会返回包含用户信息的`SubjectSum`对象
|
||||
2. 若中间认证鉴权失败,`checkIn`会抛出不同类型的认证鉴权异常,用户需根据这些异常来继续后面的流程(返回相应的请求响应)
|
||||
|
||||
为了使filter在springboot生效 需要在boot启动类加注解 `@ServletComponentScan`
|
||||
|
||||
````
|
||||
@SpringBootApplication
|
||||
@ServletComponentScan
|
||||
public class BootstrapApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BootstrapApplication.class, args);
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
### 一切完毕,验证测试
|
||||
|
||||
通过上面的步骤 我们的一个完整功能认证鉴权项目就搭建完成了,有同学想 就这几步骤 它的完整功能体现在哪里啊 能支持啥。
|
||||
|
||||
这个搭好的认证鉴权项目基于rbac权限模型,支持 baisc 认证,digest认证, jwt认证。能细粒度的控制用户对后台提供的restful api的访问权限,即哪些用户能访问哪些api。 我们这里来测试一下。
|
||||
|
||||
IDEA上启动工程项目。
|
||||
|
||||
##### basic认证测试
|
||||
|
||||
资源api/v1/source2===get没有配置到文本数据源里,代表所有角色或无角色都可以访问 前提是认证成功,用该资源来做认证测试
|
||||
|
||||
**认证成功**:
|
||||
|
||||

|
||||
|
||||
|
||||
**密码错误**:
|
||||
|
||||

|
||||
|
||||
|
||||
**账户不存在**:
|
||||
|
||||

|
||||
|
||||
|
||||
##### digest认证测试
|
||||
|
||||
**注意如果密码配置了加密盐,则无法使用digest认证**
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
##### jwt认证测试
|
||||
|
||||
jwt认证首先你得拥有一个签发的jwt,创建如下api接口提供jwt签发- `/api/v1/account/auth`
|
||||
````
|
||||
@RestController()
|
||||
public class AccountController {
|
||||
|
||||
private static final String APP_ID = "appId";
|
||||
/**
|
||||
* account data provider
|
||||
*/
|
||||
private SurenessAccountProvider accountProvider = new DocumentAccountProvider();
|
||||
|
||||
/**
|
||||
* login, this provider a get jwt api, convenient to test other api with jwt
|
||||
* @param requestBody request
|
||||
* @return response
|
||||
*
|
||||
*/
|
||||
@PostMapping("/api/v1/account/auth")
|
||||
public ResponseEntity<Object> login(@RequestBody Map<String,String> requestBody) {
|
||||
if (requestBody == null || !requestBody.containsKey(APP_ID)
|
||||
|| !requestBody.containsKey("password")) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
String appId = requestBody.get("appId");
|
||||
String password = requestBody.get("password");
|
||||
SurenessAccount account = accountProvider.loadAccount(appId);
|
||||
if (account == null || account.isDisabledAccount() || account.isExcessiveAttempts()) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
}
|
||||
if (account.getPassword() != null) {
|
||||
if (account.getSalt() != null) {
|
||||
password = Md5Util.md5(password + account.getSalt());
|
||||
}
|
||||
if (!account.getPassword().equals(password)) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
// Get the roles the user has - rbac
|
||||
List<String> roles = account.getOwnRoles();
|
||||
long refreshPeriodTime = 36000L;
|
||||
// issue jwt
|
||||
String jwt = JsonWebTokenUtil.issueJwt(UUID.randomUUID().toString(), appId,
|
||||
"token-server", refreshPeriodTime >> 1, roles,
|
||||
null, Boolean.FALSE);
|
||||
Map<String, String> body = Collections.singletonMap("token", jwt);
|
||||
return ResponseEntity.ok().body(body);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
````
|
||||
|
||||
**请求api接口登录认证获取jwt**
|
||||
|
||||

|
||||
|
||||
|
||||
**携带使用获取的jwt值请求api接口**
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
|
||||
##### 鉴权测试
|
||||
|
||||
通过上面的sureness.yml文件配置的用户-角色-资源,我们可以关联下面几个典型测试点
|
||||
1. `/api/v1/source3===get`资源可以被任何直接访问,不需要认证鉴权
|
||||
2. `api/v1/source2===get`资源持所有角色或无角色访问 前提是认证成功
|
||||
3. 用户admin能访问`/api/v1/source1===get`资源,而用户root,tom无权限
|
||||
4. 用户tom能访`/api/v1/source1===delete`资源,而用户admin.root无权限
|
||||
测试如下:
|
||||
|
||||
**`/api/v1/source3===get`资源可以被任何直接访问,不需要认证鉴权**
|
||||

|
||||
|
||||
**`api/v1/source2===get`资源持所有角色或无角色访问 前提是认证成功**
|
||||

|
||||
|
||||
**用户admin能访问`/api/v1/source1===get`资源,而用户root,tom无权限**
|
||||

|
||||

|
||||
|
||||
**用户tom能访`/api/v1/source1===delete`资源,而用户admin.root无权限**
|
||||

|
||||

|
||||
|
||||
|
||||
### 其他
|
||||
|
||||
这次图文一步一步的详细描述了构建一个简单但完整的认证鉴权项目的流程,当然里面的授权账户等信息是写在配置文件里面的,实际的项目是会把这些数据写在数据库中。
|
||||
万变不离其宗,无论是写配置文件还是数据库,它只是作为数据源提供数据,基于sureness我们也能轻松快速构建基于数据库的认证鉴权项目,支持动态刷新等各种功能。
|
||||
|
||||
基于数据库方案的项目可参考下方样例->sureness集成springboot样例(数据库方案), 此次一步一步完成的系统源代码也在下方 -> sureness集成springboot样例(配置文件方案)
|
||||
|
||||
<br>
|
||||
|
||||
#### DEMO源代码仓库
|
||||
|
||||
- [x] sureness集成springboot样例(配置文件方案) [sample-bootstrap](https://github.com/tomsun28/sureness/tree/master/sample-bootstrap)
|
||||
- [x] sureness集成springboot样例(数据库方案) [sample-tom](https://github.com/tomsun28/sureness/tree/master/sample-tom)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user