I have to call web service through java. When i hit the web-service URL in browser it asks for user name and password and i can see the result,
But when i am trying to call it using java code i am getting error like
You are not authorized to view this page BODY { font: 8pt/12pt verdana } H1 { font: 13pt/15pt verdana } H2 { font: 8pt/12pt verdana } A:link { color: red } A:visited { color: maroon }You are not authorized to view this pageYou do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.Please try the following:Contact the Web site administrator if you believe you should be able to view this directory or page.Click the Refresh button to try again with different credentials.HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.Internet Information Services (IIS)Technical Information (for support personnel)Go to Microsoft Product Support Services and perform a title search for the words HTTP and 401.Open IIS Help, which is accessible in IIS Manager (inetmgr), and search for topics titled About Security, Authentication, and About Custom Error Messages.
i am not able access the the result using SOAP UI
i am really stuck ,i tried using httpclient/jersey
please help how can i send username and password using java code
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class NTLM_TRY2 {
/**
* #param args
*/
public static void main(String[] args) throws Exception{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://10.0.134.114/eBill/bpsWebService.asmx");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("abc", "acb#578", "", ""));
java.util.List<String> authtypes = new ArrayList<String>();
authtypes.add(AuthPolicy.NTLM);
authtypes.add(AuthPolicy.DIGEST);
authtypes.add(AuthPolicy.BASIC);
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF,
authtypes);
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
authtypes);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
HttpResponse response = httpclient.execute(httpget, localContext);
System.out.println("Response code: " + response.getStatusLine());
}
}
If it is basic authentication you have to send the user an password in the header of the request.
See this question in SO.
Http Basic Authentication in Java using HttpClient?
Related
I am trying to using an openAM external identity provider to authenticate users of the WSO2 developer portal.
To do that I need to dynamically add the role Internal/subscriber to user authenticated via openAM because we don't have roles in openAM.
So I added the following code to the Script Based Adaptive Authentication:
var onLoginRequest = function(context) {
executeStep(1, {
onSuccess: function (context) {
// Extracting authenticated subject from the first step.
var user = context.currentKnownSubject;
assignUserRoles(user, ['Internal/subscriber']);
}
});
};
Trying the authentication I see in the wso2 logs the error "assignUserRoles" is not defined:
TID: [-1234] [] [2021-06-10 10:57:34,273] ERROR {org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder} - Error in executing the javascript for service provider : apim_devportal, Javascript Fragment :
function (context) {
// Extracting authenticated subject from the first step.
var user = context.currentKnownSubject;
assignUserRoles(user, ['Internal/subscriber']);
} <eval>:4 ReferenceError: "assignUserRoles" is not defined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1442)
Any idea on how to solve this? Or any other alternative to give a default Internal/subscriber to any user authenticated via OpenAM?
The above-mentioned error is expected in the API Manager servers. This is because the API Manager servers are not built to support Adaptive Authentication as WSO2 IS servers.
So, if you are planning to perform the Adaptive Authentication, the best option would be to deploy a WSO2 IS server as a Key Manager with API Manager and perform the task. Further, as an alternative way, we can implement a custom Provisioning Handler to assign the `Internal/subscriber' role to the provisioning users.
You can refer to the SystemRolesRetainedProvisionHandler.java implementation for more clarity. We can make use of the retrieveRolesToBeDeleted() to append the Internal/subscriber role into the rolesToAdd variable and then configure the custom provisioning handler in the API Manager with the following TOML config
[authentication.framework.extensions]
provisioning_handler = "com.sample.custom.CustomRoleProvisioningHandler"
A sample implementation is given below
// CustomRoleProvisioningHandler.java
import java.util.List;
import java.util.Map;
import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException;
import org.wso2.carbon.identity.application.authentication.framework.handler.provisioning.impl.DefaultProvisioningHandler;
import org.wso2.carbon.identity.application.authentication.framework.handler.provisioning.impl.SystemRolesRetainedProvisionHandler;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
public class CustomRoleProvisioningHandler extends SystemRolesRetainedProvisionHandler {
#Override
public void handle(List<String> roles, String subject, Map<String, String> attributes,
String provisioningUserStoreId, String tenantDomain) throws FrameworkException {
roles.add("Internal/subscriber");
super.handle(roles, subject, attributes, provisioningUserStoreId, tenantDomain);
}
}
Further here are few other implementations for custom provisioning handlers
tharakawijekoon/custom-provisioning-handler
nipunthathsara/wso2-custom-provisioning-handler
Hope this helps to achieve your requirement.
I'm really new to using retrofit2. I'm trying to send access token to the backend from mobile app and authenticate the user via Google but I can not do it properly. The backend returns 400.
My code is like this.
views.py
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
urls.py
path('rest-auth/google/', GoogleLogin.as_view()),
And my Java code (I'm using retrofit2)
public interface ApiService {
// login
#POST("/rest-auth/google/")
Call<String> login(#Header("access_token") String accessToken);
MainActivity.java
private void login() {
ApiService service = ApiClient.getService();
service.login(mAuthToken).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Code:" + response.code(), Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mTextViewResult.setText(t.getMessage());
}
});
}
mAuthToken is access token. I think I'm wrong with the way to pass the access token to backend. I might be wrong with retrofit2 part. What am I wrong with this?
Update
I found a thing. The access token I get in Android and the access token I get when I login via website is apparently different. I deleted the user and input the access token in the html form manually, the request is accepted.
So I guess there is a problem with access token I get in Android but I have no idea how I can fix this.
I'm trying to set up a basic website (serverless on AWS) that would allow visitors to login with Google and/or Facebook. Currently I'm planning to use S3, Cognito with Federated Identities, API Gateway, Lambda (NodeJS), with DynamoDB. The client app will be using Angular.
I have the social login with Google and Facebook working, and currently I am inserting a row in a "users" table when a user logs in the first time that includes the cognitoId, name, profile picture URL, etc.
I also figure it would be a good design to store the user's information with their email address as the key, instead of something like the cognitoId so that the user can login using different Providers and see the same data. So I need to know the authenticated user's email address, but I figure it should come from Cognito and not straight from the user (since the client app shouldn't be trusted).
I believe that Cognito is storing the user's email address because I have enabled that field as required int the User Pool.
The issue I'm having is that I cannot find any information about how to get the user's email address from Cognito.
The closest that I've come is this post, but I can't find the access token anywhere: How to get user attributes (username, email, etc.) using cognito identity id
This post indicates that I may be able to use GetUser, but I again don't know where the AccessToken comes from: creating user using AWS cognito identity
If I do need to use GetUser and the AccessToken, where does it come from, and how do I generate it? Does it come from the client, or can I get it in Lambda using AWS.config.credentials?
I've been trying to figure this out for a while now and I'm feeling like I'm missing something really simple!
Firstly, go into Cognito Identity provider (in the Cognito console) and make sure your provider "Authorize Scope" is suitable. For example if you clicked on the Google provider your Authorize scope might be "profile email openid". The scope will vary by provider, but whatever scope you are using, it must provide access to the users email.
When your user logs in with an external identity provider (lets say Facebook), Cognito negotiates with Facebook and then calls your Callback URL, which is set in the 'App Client Settings' part of the Cognito console. That Callback contains a parameter called 'code' - the parameter is set in the URL of the Callback made my Cognito. The code is an OAuth token.
Now you have an OAuth token in your client you need to POST that to the AWS Token Endpoint. The token endpoint returns three new tokens in the response; a JWT ID Token, a JWT Access Token and a refresh token. Take the "id_token" attribute from the endpoint response. Parse that id_token as a json string, and take the 'email' element. Now you should have the users email address.
Here is my working example in Java. This is a servlet that gets called by the Cognito Callback.
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.nimbusds.jwt.SignedJWT;
import net.minidev.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class CognitoLandingServlet extends HttpServlet {
static final Logger LOG = LoggerFactory.getLogger(CognitoLandingServlet.class);
private static final long serialVersionUID = 1L;
public CognitoLandingServlet() {
super();
}
#Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// Get the OpenID Connect (OAuth2) token passed back from the hosted Cognito
// Login Page
final String code = request.getParameter("code");
LOG.debug(String.format("Cognito OAuth2 code received from Cognito: %s.", code));
if (code != null) {
// do nothing, we have a code as expected
} else {
LOG.debug(String.format(
"Landing page requested without a Cognito code, the request probably didn't come from Cognito"));
// we dont have a token so redirect the user to the application sign in
// page
request.getRequestDispatcher("/signin").forward(request, response);
}
// Exchange the OIDC token for Cognito Access and ID JWT tokens using AWS
// Token
// Endpoint
// There does not appear to be a Java SDK to handle this :(
final String cognitoClientId = System.getProperty("CognitoClientId");
final String redirectUri = System.getProperty("CognitoCallBackUrl");
final String awsTokenEndpoint = System.getProperty("AwsTokenEndpoint");
final String jwt = swapOauthForJWT(cognitoClientId, code, redirectUri, awsTokenEndpoint);
// Complete the login using the JWT token string
loginWithJWT(jwt, request, response);
}
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
}
private void loginWithJWT(final String jwtString, final HttpServletRequest request,
final HttpServletResponse response) {
final JSONParser parser = new JSONParser();
SignedJWT signedIdJWT;
try {
// Take the id token
final JSONObject json = (JSONObject) parser.parse(jwtString);
final String idToken = (String) json.get("id_token");
// Access token is not currently used
// String accessToken = (String) json.get("access_token");
// Process the id token
signedIdJWT = SignedJWT.parse(idToken);
final String userId = signedIdJWT.getJWTClaimsSet().getSubject();
// Start NEW Session and start adding attributes
final HttpSession session = request.getSession(true);
session.setAttribute("userId", userId);
final String cognitoUsername = (String) signedIdJWT.getJWTClaimsSet()
.getClaim("cognito:username");
if (cognitoUsername != null) {
user.setUserName(cognitoUsername);
session.setAttribute("username", cognitoUsername);
}
final String email = (String) signedIdJWT.getJWTClaimsSet().getClaim("email");
if (email != null) {
user.setEmail(email);
session.setAttribute("email", email);
}
// Save the user to a database (code removed for stack overflow)
//request.getRequestDispatcher("/dashboard").forward(request, response);
response.sendRedirect("/dashboard");
LOG.info(
String.format("A user with userid %s and email %s successfully signed in", userId, email));
} catch (final java.text.ParseException e) {
LOG.error(
String.format("The JWT token could not be parsed by JOSE library. %s", e.getMessage()));
} catch (final ParseException e) {
LOG.error(String.format("The JWT token could not be parsed by JSON simple library. %s",
e.getMessage()));
} catch (final IOException e) {
LOG.error(String.format("Failed to request webpage at the end of the login process - io. %s",
e.getMessage()));
}
}
private String swapOauthForJWT(final String cognitoClientId, final String oauthCode,
final String redirectUri, final String awsTokenEndpoint) throws IOException {
// Build the URL to post to the AWS Token Endpoint
final String urlParameters = String.format(
"Content-Type=application/x-www-form-urlencoded&grant_type=authorization_code&client_id=%s&code=%s&redirect_uri=%s",
cognitoClientId, oauthCode, redirectUri);
LOG.debug(String.format("User is swapping OAuth token for a JWT using URL %s", urlParameters));
final URL url = new URL(awsTokenEndpoint);
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
final OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// Read the data returned from the AWS Token Endpoint
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
// Close the connection
writer.close();
reader.close();
LOG.debug(String.format("Finished swapping OAuth token for a JWT"));
return responseStrBuilder.toString();
}
}
You also need to add Attribute mappings in your user pool. Check if you have forgotten to add the mappings. You can find "attribute mappings" tab under "federation" inside your User Pool settings
To get the email, you have to request it to the identity provider (facebook, google, user pool).
To get the email from the user pool you have to do something like:
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
alert(err);
return;
}
for (i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
Cognito Identity doesn't save the emails.
I need to create an Http Client to test a REST web service with JAXRS Client API (lib: javax.ws.rs.client.*) provided by WLP. I'll have to send a String Request (JSON message) using POST method and Receive a String Response (JSON message). I'll be grateful if someone has a similar Java Code (Class) and the necessary imports to do this task.
PS : I started coding the Java Class but I didn't know how to get the response:
Client client = ClientBuilder.newClient();
WebTarget myResource = client.target("http://example.com/webapi");
....
I'm using:
Websphere Liberty profile 16.0.0.2,
jaxrs-2.0 [1.0.0]
jaxrsClient-2.0 [1.0.0]
IDE : RDz
You're almost there. All you need to do is format your request data into an instance of 'Entity' and send it off to your service.
Below is some example code that does this for a very simple JAX-RS service.
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
....
// Set up our client and target our JAX-RS service
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9081/example.jaxrs/test/SimpleService");
// Build our request JSON into an 'Entity'. Replace 'myData' with your JSON
Entity<String> data = Entity.entity("MyData", MediaType.APPLICATION_JSON_TYPE);
// Then send a post request to the target service
String result = target.request(MediaType.APPLICATION_JSON_TYPE).post(data, String.class);
Try the following,
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
Client client = ClientBuilder.newClient();
WebTarget myResource = client.target("http://example.com/webapi");
Invocation.Builder invocationBuilder = myResource.request(MediaType.TEXT_PLAIN_TYPE);
Response getResponse = invocationBuilder.get();
if (getResponse != null && getResponse.getStatus() == 200) {
String responseString = getResponse.readEntity(String.class);
}
When I deploy and run my web service developed with JAX-WS I can see a summary page with some info on it, something like in this picture:
http://www.mkyong.com/webservices/jax-ws/deploy-jax-ws-web-services-on-tomcat/
For the final implementation we would like to remove this page so that a custom or a blank page is returned while still having access to the web service endpoint.
We are currently running on Tomcat.
There is a field on the WSServlet class that might do what you are looking for: JAXWS_RI_PROPERTY_PUBLISH_STATUS_PAGE (it's value is com.sun.xml.ws.server.http.publishStatusPage).
Looking at the source code from a JAX-WS download it seems that you need to set it as a context parameter in your web.xml file:
<web-app>
<context-param>
<param-name>com.sun.xml.ws.server.http.publishStatusPage</param-name>
<param-value>false</param-value>
</context-param>
...
Seems that HttpAdapter had something similar on it but was taken from an environment variable:
setPublishStatus(
System.getProperty(HttpAdapter.class.getName() + ".publishStatusPage")
.equals("true"));
The code on HttpAdapter is marked deprecated in the javadoc so the context parameter seems the way to go.
I have been trying to solve this for two days, Glassfish 3.1.2.
The only solution was to have
-Dcom.sun.xml.ws.transport.http.HttpAdapter.publishStatusPage=false
I know its old, but wantd to maintain the knowledge. Hope this helps any one with this issue.
I have completed the same task for WebLogic recently.
It was requested to hide/show a status page of a public web service depending on a target environment i.e. hide for production, show for dev.
Nothing of the previous answers worked for me.
The success solution is based on implementation of javax.servlet.Filter.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
#WebFilter(urlPatterns = { "/WeblogicWebService" })
public class FilterStatusSoapPage implements Filter {
#Value("${soap.status.page.disabled}")
private boolean flagDisablePublishStatusPage;
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
String queryString = httpReq.getQueryString();
if(flagDisablePublishStatusPage)
if(queryString == null || queryString.trim().isEmpty())
if(HttpMethod.GET.matches(httpReq.getMethod())) {
httpRes.setStatus(HttpServletResponse.SC_OK);
httpRes.getWriter().write("Access to status page of Web
Service is not allowed");
httpRes.getWriter().flush();
httpRes.getWriter().close();
return;
}
} catch (Exception e) {
System.err.println("Error on FilterStatusSoapPage filter");
chain.doFilter(request, response);
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
}