首先,不要对移动应用程序使用 HTTP 会话身份验证。
另一方面,Oauth2 或 JWT 可以很好地与移动应用程序配合使用。他们背后的基本想法是获得token从 Jhipster 到移动设备,令牌有一个过期时间。届时您可以使用令牌访问 Jhipster 的任何 REST API 来访问数据。
下面我展示了如何在基于 angularjs 的 ionic 应用程序中使用 Jhipster Rest API 的代码片段。我希望它能让您了解您需要做什么。
取消application.yml里面cors的注释jhipster
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);
});
Here "YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24=" is equal to (clientId + ":" + clientSecret)--all base64-encoded
上面的 $http 如果成功的话会给你这个包含 token 和过期时间的 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);
});