blob: 7064c258cfa24d0dcc65ac3587c10b290ddd5b47 [file] [log] [blame]
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="../../img/favicon.ico" />
<title>Authentication - ServiceComb Java Chassis 开发指南</title>
<link rel="stylesheet" href="../../css/theme.css" />
<link rel="stylesheet" href="../../css/theme_extra.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/github.min.css" />
<script>
// Current page data
var mkdocs_page_name = "Authentication";
var mkdocs_page_input_path = "featured-topics/application-porter/authentication.md";
var mkdocs_page_url = null;
</script>
<script src="../../js/jquery-3.6.0.min.js" defer></script>
<!--[if lt IE 9]>
<script src="../../js/html5shiv.min.js"></script>
<![endif]-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../../index.html" class="icon icon-home"> ServiceComb Java Chassis 开发指南
</a>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../toc.html">目录</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../index.html">概述</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../start/catalog.html">快速入门</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../start/design.html">设计选型参考</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../build-provider/definition/service-definition.html">微服务定义</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../build-provider/catalog.html">开发服务提供者</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../build-consumer/catalog.html">开发服务消费者</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../general-development/catalog.html">通用功能开发</a>
</li>
</ul>
<p class="caption"><span class="caption-text">多样化的通信协议功能参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../transports/introduction.html">多协议介绍</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../transports/rest-over-servlet.html">REST over Servlet</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../transports/rest-over-vertx.html">REST over Vertx</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../transports/http2.html">REST over HTTP2</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../transports/highway-rpc.html">Highway</a>
</li>
</ul>
<p class="caption"><span class="caption-text">多样化的服务注册与发现功能参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../registry/introduction.html">注册发现说明</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../registry/service-center.html">使用服务中心</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../registry/local-registry.html">本地注册发现</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../registry/distributed.html">去中心化注册发现</a>
</li>
</ul>
<p class="caption"><span class="caption-text">管理服务配置</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../config/general-config.html">通用配置说明</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../config/read-config.html">在程序中读取配置信息</a>
</li>
</ul>
<p class="caption"><span class="caption-text">服务治理功能参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/intruduction.html">处理链介绍</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/loadbalance.html">负载均衡</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/ratelimit.html">限流</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/router.html">灰度发布</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/fault-injection.html">故障注入</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/governance.html">流量特征治理</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/fail-retry.html">快速失败和重试</a>
</li>
</ul>
<p class="caption"><span class="caption-text">网关功能参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../edge/open-service.html">介绍</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../edge/by-servicecomb-sdk.html">使用 Edge Service 做网关</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../edge/zuul.html">使用 `zuul` 和 `spring cloud gateway` 做网关</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../edge/nginx.html">nginx 网关简单介绍</a>
</li>
</ul>
<p class="caption"><span class="caption-text">安全特性参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../references-handlers/publickey.html">公钥认证</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../security/tls.html">使用TLS通信</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../security/shi-yong-rsa-ren-zheng.html">使用RSA认证</a>
</li>
</ul>
<p class="caption"><span class="caption-text">服务打包和运行</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../packaging/standalone.html">以standalone模式打包</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../packaging/web-container.html">以WEB容器模式打包</a>
</li>
</ul>
<p class="caption"><span class="caption-text">专题文章</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../using-java-chassis-in-spring-boot/using-java-chassis-in-spring-boot.html">在Spring Boot中使用java chassis</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../features.html">新功能介绍系列文章</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../compatibility.html">兼容问题和兼容性策略</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../upgrading.html">升级指导系列文章</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../performance.html">性能问题分析和调优</a>
</li>
</ul>
<p class="caption"><span class="caption-text">常用配置项参考</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../config-reference/rest-transport-client.html">REST Transport Client 配置项</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../config-reference/config-center-client.html">Config Center Client 配置项</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../config-reference/service-center-client.html">Service Center Client 配置项</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../config-reference/kie-client.html">ServiceComb Kie Client 配置项</a>
</li>
</ul>
<p class="caption"><span class="caption-text">常见问题</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../question-and-answer/faq.html">FAQ</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../question-and-answer/question_answer.html">Q & A</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../question-and-answer/interface-compatibility.html">微服务接口兼容常见问题</a>
</li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="Mobile navigation menu">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../index.html">ServiceComb Java Chassis 开发指南</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content"><div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../index.html" class="icon icon-home" alt="Docs"></a> &raquo;</li>
<li>Authentication</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div class="section" itemprop="articleBody">
<p>传统的WEB容器都提供了会话管理,在微服务架构下,这些会话管理存在很多的限制,如果需要做到弹性扩缩容,则需要做大量的定制。 在porter中,我们使用user-service做会话管理,可以通过login和session两个接口创建和获取会话信息。会话信息持久化到数据库中,从而实现微服务本身的无状态,微服务可以弹性扩缩容。在更大规模并发或者高性能要求的情况下,可以考虑将会话信息存储到高速缓存。</p>
<pre><code>@PostMapping(path = &quot;/login&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public SessionInfo login(@RequestParam(name = &quot;userName&quot;) String userName,
@RequestParam(name = &quot;password&quot;) String password)
@GetMapping(path = &quot;/session&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public SessionInfo getSession(@RequestParam(name = &quot;sessionId&quot;) String sessionId)
</code></pre>
<p>同时新增了会话管理的数据表设计:</p>
<pre><code>CREATE TABLE `T_SESSION` (
`ID` INTEGER(8) NOT NULL AUTO_INCREMENT COMMENT '唯一标识',
`SESSION_ID` VARCHAR(64) NOT NULL COMMENT '临时会话ID',
`USER_NAME` VARCHAR(64) NOT NULL COMMENT '用户名称',
`ROLE_NAME` VARCHAR(64) NOT NULL COMMENT '角色名称',
`CREATION_TIME` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`ACTIVE_TIME` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近活跃时间',
PRIMARY KEY (`ID`)
);
</code></pre>
<p>会话管理和认证都在gateway-service进行,鉴权则需要使用到用户信息。为了让微服务获取用户信息的时候,不至于再查询user-service,我们利用了Context机制,在Context里面存储了session信息,所有的微服务都可以直接从Context里面取到session信息,非常方便和灵活。完成这个功能有如下几个关键步骤:</p>
<ul>
<li>gateway-service进行HTTP协议到Invocation的转换</li>
</ul>
<p>这个通过重载EdgeInvocation的createInvocation实现。将会话ID通过Context传递给handler。如果开发者需要实现诸如增加响应头,设计Cookie等操作,则可以通过重载sendResponse来实现。</p>
<pre><code>EdgeInvocation invoker = new EdgeInvocation() {
// 认证鉴权:构造Invocation的时候,设置会话信息。如果是认证请求,则添加Cookie。
protected void createInvocation(Object[] args) {
super.createInvocation(args);
// 既从cookie里面读取会话ID,也从header里面读取,方便各种独立的测试工具联调
String sessionId = context.request().getHeader(&quot;session-id&quot;);
if (sessionId != null) {
this.invocation.addContext(&quot;session-id&quot;, sessionId);
} else {
Cookie sessionCookie = context.getCookie(&quot;session-id&quot;);
if (sessionCookie != null) {
this.invocation.addContext(&quot;session-id&quot;, sessionCookie.getValue());
}
}
}
};
</code></pre>
<ul>
<li>通过handler来进行认证和会话管理</li>
</ul>
<p>对于ui界面,不提供认证,用户可以直接访问。对于REST接口需要进行认证,因此我们将认证和会话管理的功能在Hanlder中实现。下面的代码对user-service的login接口直接转发请求,其他请求先经过会话校验,再进行转发。</p>
<p><strong><em>注意</em></strong>: 在网关执行的Hanlder逻辑,是reactive模式的,不能使用阻塞调用,否则会导致线程阻塞。</p>
<pre><code>public class AuthHandler implements Handler {
private UserServiceClient userServiceClient = BeanUtils.getBean(&quot;UserServiceClient&quot;);
// session expires in 10 minutes, cache for 1 seconds to get rid of concurrent scenarios.
private Cache&lt;String, String&gt; sessionCache = CacheBuilder.newBuilder()
.expireAfterAccess(30, TimeUnit.SECONDS)
.build();
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
if (invocation.getMicroserviceName().equals(&quot;user-service&quot;)
&amp;&amp; (invocation.getOperationName().equals(&quot;login&quot;)
|| (invocation.getOperationName().equals(&quot;getSession&quot;)))) {
// login:return session id, set cookie by javascript
invocation.next(asyncResponse);
} else {
// check session
String sessionId = invocation.getContext(&quot;session-id&quot;);
if (sessionId == null) {
throw new InvocationException(403, &quot;&quot;, &quot;session is not valid.&quot;);
}
String sessionInfo = sessionCache.getIfPresent(sessionId);
if (sessionInfo != null) {
try {
// session info stored in InvocationContext. Microservices can get it.
invocation.addContext(&quot;session-id&quot;, sessionId);
invocation.addContext(&quot;session-info&quot;, sessionInfo);
invocation.next(asyncResponse);
} catch (Exception e) {
asyncResponse.complete(Response.failResp(new InvocationException(500, &quot;&quot;, e.getMessage())));
}
return;
}
// In edge, handler is executed in reactively. Must have no blocking logic.
CompletableFuture&lt;SessionInfo&gt; result = userServiceClient.getGetSessionOperation().getSession(sessionId);
result.whenComplete((info, e) -&gt; {
if (result.isCompletedExceptionally()) {
asyncResponse.complete(Response.failResp(new InvocationException(403, &quot;&quot;, &quot;session is not valid.&quot;)));
} else {
if (info == null) {
asyncResponse.complete(Response.failResp(new InvocationException(403, &quot;&quot;, &quot;session is not valid.&quot;)));
return;
}
try {
// session info stored in InvocationContext. Microservices can get it.
invocation.addContext(&quot;session-id&quot;, sessionId);
String sessionInfoStr = JsonUtils.writeValueAsString(info);
invocation.addContext(&quot;session-info&quot;, sessionInfoStr);
invocation.next(asyncResponse);
sessionCache.put(sessionId, sessionInfoStr);
} catch (Exception ee) {
asyncResponse.complete(Response.failResp(new InvocationException(500, &quot;&quot;, ee.getMessage())));
}
}
});
}
}
}
</code></pre>
<p>启用该Hanlder,需要增加cse.handler.xml文件</p>
<pre><code>&lt;config&gt;
&lt;handler id=&quot;auth&quot;
class=&quot;org.apache.servicecomb.samples.porter.gateway.AuthHandler&quot; /&gt;
&lt;/config&gt;
</code></pre>
<p>并且在microservice.yaml中启用auth,将新增加的auth处理链放到流控之后。</p>
<pre><code>servicecomb:
handler:
chain:
Consumer:
default: internalAccess,auth,qps-flowcontrol-consumer,loadbalance
</code></pre>
<ul>
<li>给删除文件增加鉴权</li>
</ul>
<p>在上面的步骤中,已经将会话信息设置到Context里面,file-service可以方便的使用这些信息进行鉴权操作。</p>
<pre><code>@DeleteMapping(path = &quot;/delete&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public boolean deleteFile(@RequestParam(name = &quot;id&quot;) String id) {
String session = ContextUtils.getInvocationContext().getContext(&quot;session-info&quot;);
if (session == null) {
throw new InvocationException(403, &quot;&quot;, &quot;not allowed&quot;);
} else {
SessionInfo sessionInfo = null;
try {
sessionInfo = JsonUtils.readValue(session.getBytes(&quot;UTF-8&quot;), SessionInfo.class);
} catch (Exception e) {
throw new InvocationException(403, &quot;&quot;, &quot;session not allowed&quot;);
}
if (sessionInfo == null || !sessionInfo.getRoleName().equals(&quot;admin&quot;)) {
throw new InvocationException(403, &quot;&quot;, &quot;not allowed&quot;);
}
}
return fileService.deleteFile(id);
}
</code></pre>
<p>到这里为止,认证、会话管理和鉴权的逻辑基本已经完成了。可以通过Postman等工具进行流程相关的测试。</p>
<pre><code>#### 会话管理接口调用示例,调用删除文件接口。使用guest用户的会话的情况。
#Request
DELETE http://localhost:9090/api/file-service/delete?id=ba6bd8a2-d31a-42cd-a1be-9fb3d6ab4c82
session-id: 1be646c0-50cb-4c0a-968d-2a512775f5e8
#Response
{
&quot;message&quot;: &quot;not allowed&quot;
}
</code></pre>
<h1 id="js">开发JS脚本管理会话</h1>
<p>首先需要提供登陆框,让用户输入用户名密码:</p>
<pre><code>&lt;div class=&quot;form&quot;&gt;
&lt;h2&gt;登录&lt;/h2&gt;
&lt;input id=&quot;username&quot; type=&quot;text&quot; name=&quot;Username&quot; placeholder=&quot;Username&quot;&gt;
&lt;input id=&quot;paasword&quot; type=&quot;password&quot; name=&quot;Password&quot; placeholder=&quot;Password&quot; &gt;
&lt;input type=&quot;button&quot; value=&quot;Login&quot; onclick=&quot;loginAction()&quot;&gt;
&lt;/div&gt;
</code></pre>
<p>实现登陆逻辑。登陆首先调用后台登陆接口,登陆成功后设置会话cookie:</p>
<pre><code>function loginAction() {
var username = document.getElementById(&quot;username&quot;).value;
var password = document.getElementById(&quot;paasword&quot;).value;
var formData = {};
formData.userName = username;
formData.password = password;
$.ajax({
type: 'POST',
url: &quot;/api/user-service/login&quot;,
data: formData,
success: function (data) {
setCookie(&quot;session-id&quot;, data.sessiondId, false);
window.alert('登陆成功!');
},
error: function(data) {
console.log(data);
window.alert('登陆失败!' + data);
},
async: true
});
}
</code></pre>
</div>
</div><footer>
<hr/>
<div role="contentinfo">
<!-- Copyright etc -->
</div>
Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" role="note" aria-label="Versions">
<span class="rst-current-version" data-toggle="rst-current-version">
</span>
</div>
<script>var base_url = '../..';</script>
<script src="../../js/theme_extra.js" defer></script>
<script src="../../js/theme.js" defer></script>
<script src="../../search/main.js" defer></script>
<script defer>
window.onload = function () {
SphinxRtdTheme.Navigation.enable(true);
};
</script>
</body>
</html>