I am using Apache LDAP API to set new attribute: userPassword in Oracle Internet Directory. I want to set this password with SHA encryption method. I currently have following code:
Attribute userPasswordAttribute = new DefaultAttribute("userPassword", "password"));
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName(dn);
modifyRequest.add(userPasswordAttribute);
ModifyResponse response = connection.modify(modifyRequest);
However this adds SSHA encrypted password along with some other attributes which I do not want (authpassword;oid). I have seen that there a class called EncryptionMethod in LDAP API but how to use it in my code?
Try this
String newPassword = "password";
modifyRequest.replace("userPassword", PasswordUtil.createStoragePassword(
newPassword.getBytes(), LdapSecurityConstants.HASH_METHOD_SHA));
Related
I am generating a preSignedUrl and then uploading the file through that url.
The issue is that even if I enter the wrong access key or secret key I get the preSignedUrl, though if I try to upload using that url I get 400 error.
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>AuthorizationQueryParametersError</Code>
<Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message>
<RequestId>{requestId}</RequestId>
<HostId>{hostId}</HostId>
</Error>
Is there some way I get the error while generating the preSignedUrl so that I don't have to try and upload the file.
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")))
.withRegion(clientRegion)
.build();
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
Generating a pre-signed URL doesn't require an API call; it can be generated by the framework using the specified access key and secret.
The generated URL will be validated by S3 when the request is received, and will obviously only be accepted when valid credentials were used for generating it.
Bottom line: in order to validate your credentials you need to make an API request that actually performs a call to AWS. This can be pretty much any other method on your s3Client.
Let's start with this:
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")))
Static credentials go against AWS best practice. Instead, rely on credentials provided via environment variables or an execution role (when running on EC2, ECS, or Lambda).
The only way that you can verify that the credentials are valid is to try them. You could write a small dummy file, however this may cause problems for anything that is supposed to read that file, due to eventual consistency on S3.
There's also the problem that the expiration that you give the URL may not correspond to the lifetime of the credentials.
The best solution to all of these problems is to create a role that has access to PUT the files on S3, and has a duration consistent with your URL expiration (note that the maximum is 12 hours), then explicitly assume that role in order to construct the request:
final String assumedRoleArn = "arn:aws:iam::123456789012:role/Example";
final String sessionName = "example";
final String bucketName = "com-example-mybucket";
final String objectKey = "myfile.txt";
final int expirationSeconds = 12 * 3600;
final Date expiresAt = new Date(System.currentTimeMillis() + expirationSeconds * 1000);
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.defaultClient();
AWSCredentialsProvider credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(assumedRoleArn, sessionName)
.withStsClient(stsClient)
.withRoleSessionDurationSeconds(expirationSeconds)
.build();
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).build();
URL presignedUrl = s3Client.generatePresignedUrl(bucketName, objectKey, expiresAt, HttpMethod.PUT);
I am using adal4j v1.1.2 to get token based on client certificate.
Snippet referred: Why does AcquireToken with ClientCredential fail with invalid_client (ACS50012)?
String AAD_HOST_NAME = "login.windows.net";
String AAD_TENANT_ID = "XXX";
String AAD_TENANT_ENDPOINT = "https://" + AAD_HOST_NAME + "/" + AAD_TENANT_ID + "/";
String AAD_CLIENT_ID = "XXX";
String AAD_RESOURCE_ID = "https://vault.azure.net";
String AAD_CERTIFICATE_PATH = "/XXX.pfx";
String AAD_CERTIFICATE_PASSWORD = "XXX";
String AAD_CLIENT_SECRET = "XXX";
ExecutorService service = ExecutorServiceHelper.createThreadPool(1, "azureHSMClientExecutorService-");
KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
keystore.load(new FileInputStream(AAD_CERTIFICATE_PATH),AAD_CERTIFICATE_PASSWORD.toCharArray());
String alias = keystore.aliases().nextElement();
PrivateKey key = (PrivateKey) keystore.getKey(alias, AAD_CERTIFICATE_PASSWORD.toCharArray());
X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
AsymmetricKeyCredential asymmetricKeyCredential = AsymmetricKeyCredential.create(AAD_CLIENT_ID,key, cert);
AuthenticationContext ctx = new AuthenticationContext(AAD_TENANT_ENDPOINT, false, service);
Future<AuthenticationResult> result = ctx.acquireToken(AAD_RESOURCE_ID, asymmetricKeyCredential, null);
AuthenticationResult authenticationResult = result.get();
String token = authenticationResult.getAccessToken();
This results in following auth exception
AuthenticationException: com.microsoft.aad.adal4j.AuthenticationException: {"error":"invalid_client","error_description":"AADSTS70002: Error validating credentials. AADSTS50027: Invalid JWT token. No certificate thumbprint specified in token header.\r\nTrace ID: 9719e621-d8ef-4194-93cd-a78103d5df6b\r\nCorrelation ID: f0300795-fb99-44b2-bd95-8df3975290be\r\nTimestamp: 2016-08-29 13:51:26Z"}
I'm not sure how to pass thumbprint while calling acquireToken. Is anything missing here?
According to your code, it seems that you want to authenticate with Azure Service Management API using certificate, but the code for getting access token seems to authenticate using Azure AD. You can refer to the article Authenticating Service Management Requests to know their differences.
As reference, there is a blog which introduce how to consume Windows Azure Service Management API with certificate in Java.
However, per my experience, according to the code String AAD_RESOURCE_ID = "https://vault.azure.net"; , it also seems that you want to do some management operations for Azure Key Vault. Withing the REST API reference for Azure Key Vault Management, you should get the access token with Azure Resource Manager to do those operations. So if you want to manage Key Vault, please refer to the other blog to know how to authenticate with ARM in Java.
Hope it helps.
Update:
The AAD_RESOURCE_ID for Key Vault should be like /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.KeyVault/vaults/{vault-name}, please refer to the article https://msdn.microsoft.com/en-us/library/azure/mt620025.aspx and search the keyword resource id and see as the figure below.
And you can get the resource id via Azure CLI command azure keyvault show --vault-name <your-keyvault-name>.
I am building a web application with java and using JDBC driver
please tell me if i wrong, i dont think using this block of code is secured
how should i make it secured without using "HARD CODED" password
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:mkyong","username","password");
connection.close();
taken from:
http://www.mkyong.com/jdbc/connect-to-oracle-db-via-jdbc-driver-java/
If you're building a web-app your resources should be declared externally, for example in a Tomcat Context.xml file. The password will be located there, not in your code. And keeping that secure is a matter of physical security.
Java code will be executed on the server if you mean a Tomcat web application for example. So it should be ok so.
But if you want to have more security you could create a credentials.properties file, with tomcat as owner and rights of 600. Then you read username and password from that file.
And of course you could encrypt it in the file.
EDIT: And the credentials.properties file should not be accessable over the web ;)
Try Jasypt and it should help:
http://jasypt.org/
Example (Using a .properties file mechanism):
Step1: Find out encrypted password and make a note of it for usage:
StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(userPassword);
Let's say the encryptedPassword is: G6N718UuyPE5bHyWKyuLQSm02auQPUtm
Step2: Store DB connection credentials in a .properties file with encrypted password
datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost/reportsdb
datasource.username=reportsUser
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
Step3: How do we read this value? like this:
/*
* First, create (or ask some other component for) the adequate encryptor for
* decrypting the values in our .properties file.
*/
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("jasypt"); // could be got from web, env variable...
/*
* Create our EncryptableProperties object and load it the usual way.
*/
Properties props = new EncryptableProperties(encryptor);
props.load(new FileInputStream("/path/to/my/configuration.properties"));
/*
* To get a non-encrypted value, we just get it with getProperty...
*/
String datasourceUsername = props.getProperty("datasource.username");
/*
* ...and to get an encrypted value, we do exactly the same. Decryption will
* be transparently performed behind the scenes.
*/
String datasourcePassword = props.getProperty("datasource.password");
// From now on, datasourcePassword equals "reports_passwd"...
For decrypting the encrypted value, we just had to access it with getProperty, just as with any other non-encrypted value.
Details here: http://www.jasypt.org/encrypting-configuration.html
I want my jdbcRealm to not use any Digest Algorithm in Glassfish. I want the jdbcRealm to compare against the database without converting password with any algorithm.
My password in the database is MD5 and I convert the user's password to md5 in java code and then use the code:
FacesContext context = FacesContext.getCurrentInstance ();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext (). GetRequest ();
request.login (username, md5Password);
So can I remove the Digest Algorithm so my jdbcRealm compare plain text without any algorithm?
I know I can send the user's password in plain text and the jdbcrealm will do the job for me, but I want to try this
Yes, yo can
Set Digest algorithm none
I want to realize a simple login via facebook on my website. I used SocialAuth for that and it is working pretty fine. But if i login via facebook, the facebook app needs the confirmation for a lot of access rights like, posting to the wall and so on.
I don't need this rights. Can i somehow define, which rights are requested (basically i need none - just the login). This is my code:
//Create an instance of SocialAuthConfgi object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://opensource.brickred.com/socialauthdemo/socialAuthSuccessAction.do";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl(id, successUrl);
// Store in session
session.setAttribute("authManager", manager);
My config looks something like this. Can i define this here in some way?
#facebook
graph.facebook.com.consumer_key = 152190004803645
graph.facebook.com.consumer_secret = 64c94bd02180b0ade85889b44b2ba7c4
graph.facebook.com.secure = true
graph.facebook.com.request_token_url = /oauth/access_token
graph.facebook.com.authorization_url = /oauth/authorize
graph.facebook.com.access_token_url = /me
graph.facebook.com.signature_method = HMAC-SHA1
graph.facebook.com.transport_name = GET
You can add custom permission like this.
graph.facebook.com.consumer_key = 152190004803645
graph.facebook.com.consumer_secret = 64c94bd02180b0ade85889b44b2ba7c4
graph.facebook.com.custom_permission = email,user_birthday,user_location
No need to set other properties. But if you want to set other properties, then only you can set request_token_url (for OAuth1.0), authentication_url and access_token_url. This feature is available from socialauth-4.2
graph.facebook.com.authentication_url
graph.facebook.com.access_token_url