gpt4 book ai didi

rest - Jhipster + REST 客户端 + 身份验证

转载 作者:行者123 更新时间:2023-12-04 15:09:36 29 4
gpt4 key购买 nike

我需要了解如何对 REST 客户端进行身份验证(可能是 Paw,可能是一个 android 应用程序,一个使用 AFNetworking 和 jHipster 的 iOs 应用程序,我认为,更一般地说,使用我不是专家的 spring-boot)。

虽然我能够在登录浏览器时获取 token ,并随后在以下请求中使用此 token ,但我不明白如何首先使用 RESTful 最佳实践进行身份验证。

例如,在 Paw.app 中,我可以通过基本身份验证或 Oauth2,但我不明白如何像在 Web 浏览器上一样简单地获取 session token 。

同样,在 AFNetworking 中,我能够通过基本身份验证,例如

NSString*auth=[NSString stringWithFormat:@"%@:%@", @"admin", @"admin"];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [auth base64EncodedString]];
[manager.requestSerializer setValue:authValue forHTTPHeaderField:@"Authorization"];

但是我很难理解如何使用 jHipster/spring boot 中捆绑的 session 安全性进行身份验证。

最佳答案

首先,不要对移动应用程序使用 HTTP session 身份验证。

另一方面,Oauth2 或 JWT 与移动应用程序配合良好。它们背后的基本思想是得到一个 token 从 Jhipster 到移动设备, token 有一个到期时间。在那个时候,您可以使用 token 访问 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 应用程序中获取 token
    $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 如果成功会给你这个包含 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 的 token 以访问数据,直到 token 过期,然后我们要么刷新它,要么访问新的。

例如
$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);
});

关于rest - Jhipster + REST 客户端 + 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453269/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com