【发布时间】:2019-06-03 08:46:20
【问题描述】:
部署在 Internet 上的遗留 Java 应用程序正在尝试与基于 Spring Security 的应用程序和 Intranet 上的 AuthenticationService 通信。 AuthenticationService 在发送用户名和密码时对任何用户进行身份验证。客户端代码是:
public static void ApacheHttpClient(String userID, String userPWD){
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userID, userPWD);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8080/abc/login";
try {
HttpResponse response = client.execute(
new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
int statusCode = response.getStatusLine()
.getStatusCode();
System.out.println("Response Status Code : "+statusCode);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
用于接受用户名和密码并进行身份验证的 AuthenticationService 代码。这里, String auth = request.getHeader("Authorization");总是空的
@RestController
@RequestMapping("/abc")
public class Authenticate {
@Autowired
private LoginService loginService;
@RequestMapping("/login")
public void login(HttpServletRequest request, HttpServletResponse response) {
try {
String auth = request.getHeader("Authorization");
if(auth != null && auth.length() > 6){
String userpassEncoded = auth.substring(6);
// Decode it, using any base 64 decoder
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String userpassDecoded= new String(dec.decodeBuffer(userpassEncoded));
System.out.println(" userpassDecoded = "+userpassDecoded);
}
} catch (Exception e) {
e.printStackTrace();
}
}
通常建议使用 HTTP Basic 或 Digest Authentication。我想了解从非基于 Web 的应用程序向服务发送和检索用户名/密码的方法。就像登录应该是一个 POST 方法,用户名和密码作为查询参数或路径参数等传递
【问题讨论】:
标签: java rest spring-security apache-httpclient-4.x