首先,不要对移动应用使用 HTTP 会话身份验证。
另一方面,Oauth2 或 JWT 也适用于移动应用。它们背后的基本思想是从 Jhipster 获取 token 到移动设备,该令牌具有到期时间。届时您可以使用令牌访问 Jhipster 的任何 REST API 来访问数据。
下面我将展示如何在基于 angularjs 的 ionic 应用程序中使用 Jhipster rest API 的代码 sn-p。我希望它能告诉你你需要做什么。
在 jhipster
中的 application.yml 中取消注释 cors
cors: #By default CORS are not enabled. Uncomment to enable.
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
要在 ionic 中使用 Oauth2 身份验证访问 REST API,您必须首先在 ionic 应用程序中通过以下方式获取令牌
$http({
method: "post",
url: "http://192.168.0.4:8085/[Your app name]/oauth/token",
data: "username=admin&password=admin&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=auth2Sconnectapp",
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic ' + 'YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24='
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
这里"YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24=" is equal to (clientId + ":" + clientSecret)--all base64-encoded
如果成功,上面的 $http 会给你这个 JSON,其中包含令牌和它的到期时间
{
"access_token": "2ce14f67-e91b-411e-89fa-8169e11a1c04",
"token_type": "bearer",
"refresh_token": "37baee3c-f4fe-4340-8997-8d7849821d00",
"expires_in": 525,
"scope": "read write"
}
如果您想访问任何 API,请注意“access_token”和“token_type”,这是您必须使用的。我们使用 API 发送令牌以访问数据,直到令牌过期,然后我们要么刷新它,要么访问一个新的。
例如
$http({
method: "get",
url: "http://192.168.0.4:8085/auth-2-sconnect/api/countries",
withCredentials: true,
headers: {
'Authorization':' [token_type] + [space] + [access_token] '
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});