How can I get the user and password in request in Jersey 2.4?
The client request sets user and password as below
protected HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
.credentialsForBasic("user", "123456") //these are not in header
.credentials("adminuser", "hello")
.build();
WebTarget loginTarget = webTarget.path("u").path("login");
loginTarget.register(feature);
ReturnMessage bean = loginTarget.request(MediaType.APPLICATION_JSON_TYPE).post(..
[Added] More research suggests that those values can be got in http header in JERSEY1.x, but not in 2.x
Related
I've been trying to obtain a token for oauth2 authentication to connect to a mail server using the following Java code:
public static String getAuthToken(String tenantId, String clientId, String client_secret) throws ClientProtocolException , IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost loginPost = new HttpPost("https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token");
//String scopes = "https://outlook.office365.com/IMAP.AccessAsUser.All";
String scopes = "https://outlook.office365.com/.default"; // we need this scope when we have the grand_type as client credidentials
//String encodedBody = "client_id=" + clientId + "&scope=" + scopes + "&client_secret=" + client_secret+ "&username="+mailAddress+"&password=" + EMAIL_PASSWORD + "&grant_type=password";
String encodedBody = "client_id=" + clientId + "&scope=" + scopes + "&client_secret=" + client_secret+ "&username="+mailAddress+ "&grant_type=client_credentials";
loginPost.setEntity(new StringEntity(encodedBody, ContentType.APPLICATION_FORM_URLENCODED));
loginPost.addHeader(new BasicHeader("cache-control", "no-cache"));
CloseableHttpResponse loginResponse = client.execute(loginPost);
InputStream inputStream = loginResponse.getEntity().getContent();
byte[] response = readAllBytes(inputStream);
ObjectMapper objectMapper = new ObjectMapper();
JavaType type = objectMapper.constructType(
objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, String.class));
Map<String, String> parsed = new ObjectMapper().readValue(response, type);
return parsed.get("access_token");
}
Yet if I try to get the token without having the password in the request body (if I add the password like in the commented line, all works fine), I cannot connect with that token and get the following authentication failed error:
Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed. at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732) at javax.mail.Service.connect(Service.java:366) at yk.Auth.main(Auth.java:79)
I've tried adapting the request body (changing/removing the scope etc.) but nothing changes.
What needs to be done in order to obtain a valid token without sending the password as part of the request?
Thank you!
This is a generic answer that could be improved by someone with better knowledge of MS Azure services.
You probably need a token authorized by a user to access the IMAP server. Because your OAuth2 client (identified by clientId) is not the IMAP server user - the token you get using the client_credentials grant is not usable for the IMAP server. The line you commented out uses the password grant (which is deprecated) and requires the user's password.
I think the correct way from the OAuth2 standpoint is to use the auth code flow. This way, the user (resource owner role) delegates their rights (represented by the requested scopes) to your application (OAuth2 client role) which can use them at the IMAP server (resource server role).
The auth code flow requires user interaction - the user's browser gets redirected to the OAuth2 auth endpoint, the user gets authenticated and gives consent with delegating the requested rights to your application. Then your the browser is redirect to the redirect_uri handled by your application. The request has an auth code value which can be exchanged for tokens at the token endpoint of the OAuth2 server.
If your application doesn't interact with users who could delegate their IMAP server access, you probably need to use the password grant or figure out how to make your application (identified by its client_id) an IMAP user and use the client_credentials grant (as you do now).
I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();
You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?
I am building a website using Angular 5 as frontend, and JAX-RS with Jersey as backend. The website requires the user to login using their email and password, which is sent to the API with POST. I then want the client to receive a cookie, but this is where I'm having trouble. The API sends a response with a cookie (I can see the cookie when I test it in Postman), but in Google Chrome it looks like no cookie is received, and no header is named 'Set-Cookie'.
My method that sends the cookie from the backend:
#GET
#Path("cookie")
public Response getCookies(){
NewCookie cookie1 = new NewCookie("cookie1", "test");
return Response.ok().cookie(cookie1)
.build();
}
I'm using a CORS-filter where I set AllowCredentials to true. What have I missed?
There is a module 'Module1' that authenticates a user using LDAP. The module has a class that has to make an http request to another remote service using the same login ldap credentials.
I have the LDAP class that implements the authentication in the remote service.
I do not know how to send the login credentials from Module1 to the remote service in the http header. How can I access the credentials which i used for Ldap login from Module1 programatically ? Your responses will be very much appreaciated.
You can go for Basic Authentication , in which the user credentials will be encoded and send through the Header . Do insure to secure the call from Module1 to the remote service , so essentially the call from Module1 to Remote Service will happen over HTTPS
If you're using LDAP, the authentication can be passed off like Basic. If you know the username and password, append the header "Authorization" with the value "Basic base64_token".
The base64 token is a string that is base64 encoded with your username and password in the format username:password. Ideally, this should work. Let me know if it doesn't work. In that case, we can explore options using SPNEGO.
Code for LDAP in JAVA:
public class Main
{
public static void main(String[] args)
{
//Replace username and password with your username and password
token = Base64.getEncoder().encodeToString((username + ":" + password).getBytes())
conn = (HttpURLConnection) endpoint.openConnection();
// Set the necessary header fields, which in this case is Basic
conn.addRequestProperty("Authorization", "Basic " + token);
//Continue to do what you want to do after this. This should authenticate
// you to the server
}
}
How can i call Auth Authentication using Restfull
i want to send :
Authorization: OAuth realm="Photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="137131200",
oauth_nonce="wIjqoS",
oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"
I dont khonw more about Auth. so please help.
Since you are using HTTP client, it becomes very easy to send this header as a part of request. This can be accomplished as follows:
HttpGet request = new HttpGet("http://yoursite");
String authStr = "";// Your string starting from OAuth realm="Photos",oauth_consumer_key="dpf43f3p2l4k3l03" ....
request.setHeader("Authorization", authStr );
Once you execute this request, a Authorization header is sent to the server.