How to generate password policy based password in OIM 11gr2ps2 - event-handling

I am creating a event handler to modify user password using OIM UserManager API. But now I need to consider password policy and then generate new password that is compatible with the password policy defined in OIM.
Can you please point to some APIs and Methods which can help here?

import oracle.idm.common.ipf.api.password.RandomPasswordGenerator;
import oracle.idm.common.ipf.api.password.RandomPasswordGeneratorImpl;
The classes above actually gives handle on the randomly generated password that I was looking for. The code below shows the implementation for the same.
PasswordPolicyInfo passwordPolicyInfo = ((PasswordMgmtService)Platform.getService(PasswordMgmtService.class)).getApplicablePasswordPolicy(entityId, Boolean.valueOf(false));
RandomPasswordGenerator randomPasswordGenerator = new RandomPasswordGeneratorImpl();
OimPasswordPolicy policy = new OimPasswordPolicy(Utils.getIpfPasswordPolicyInfoVO(passwordPolicyInfo));
policy.setId(passwordPolicyInfo.getId());
policy.setName(passwordPolicyInfo.getName());
char[] generatedPassword = randomPasswordGenerator.generatePassword(policy, null);

Alternatively by using below OIM API's,you can generate password and also validate it against any policy in OIM:
import oracle.iam.passwordmgmt.api.PasswordMgmtService;
import oracle.iam.passwordmgmt.domain.generator.RandomPasswordGeneratorImpl;
Here is the snippet:
RandomPasswordGeneratorImpl randomPasswordGenerator = new RandomPasswordGeneratorImpl();
UserRepository userRepository = new DBUserRepository();
UserInfo usrInfo = userRepository.getUserAndManagerInfo(usrLogin);
String generatedPassword = new String(randomPasswordGenerator.generatePassword(Utils.getUser(usrInfo)));
PasswordMgmtService passMgmt = Platform.getService(PasswordMgmtService.class);
ValidationResult result = passMgmt.validatePasswordAgainstPolicy(generatedPassword.toCharArray(), Utils.getUser(usrInfo), Locale.getDefault());

You can use PasswordMgmtService api provided by OIM.
You can use below method in you password generation logic in your event handler code.
PasswordPolicyDescription getApplicablePasswordPolicyDescription(java.lang.String userID)
In the PasswordPolicyDescription object you have all properties which were configured while creating Password Policy.

Related

Build Jenkins pipeline using HttpRequest

I try to execute a jenkins pipeline from a Scala app, but the authentication is required. So, I think before this request, I need to call the auth endpoint and get a token, then assign it on the headers.
val userToken = "user_token_generated_in_jenkins"
val pipelineToken = "pipeline_token"
val pipelineName = "HttpRequestTest"
// test1
val baseUrl = s"http://jenkins_address/view/Development/job/$pipelineName/build?token=$pipelineToken"
val response = Http(baseUrl).headers("token" -> "tried_a_valid_token_auth").asString
// test2
val url = s"http://auto:$userToken#jenkins_address/job/$pipelineName/build?token=$pipelineToken"
val response2 = Http(url).asString
If I can be sure that first test is wrong, why for test2, where I use the user token (generated in Users manager), it asks me to use extra token (generated by authentication)? Is a double verification and useless in my opinion.
As an emergency solution, I can execute the pipeline with curl using sys.process. But I prefer to solve it using Http library because I want to use generated token and not a specific username in my project code.
// test3
import sys.process._
val data = List("curl", "-u", "username:password", baseUrl).!!
How can I execute an HttpRequest using Jenkins User Token?
Thanks
If your Http(..) is from Akk-HTTP, the solution could be derived from here:
val authorization = headers.Authorization(BasicHttpCredentials("username", "password"))
HttpRequest(
PUT,
uri = "/user",
entity = HttpEntity(`text/plain` withCharset `UTF-8`, userData),
headers = List(authorization),
protocol = `HTTP/1.0`)
In case of scalaj-http it could be derived from here
With applying to your existing code, it should be like this:
Http(baseUrl).auth("username", "password").asString
By the way
I want to use generated token and not a specific username in my
project code
It is not a problem. You can construct your process' auth string dynamically. You are able to get the credentials from somewhere in the "native" Http solution, right? So you can construct your sys.process with the same getted-from-somewhere credentials by concatinating strings or string interpolation:
// test3
import sys.process._
val (username, password) = gettingFromSomewhereCreadentials()
val data = List("curl", "-u", s"$username:$password", baseUrl).!!

How to obtain an access token within a Keycloak SPI?

Use case:
From inside a EventListenerProvider on an event I want to make an authenticated REST call to one of our keycloak secured service. For this I need a token.
First I just test printing the token to check whether it is succeeded.
public void onEvent(final Event event) {
Keycloak k = Keycloak.getInstance("http://localhost:8080/auth", "myrealm", "myemail#gmail.com", "password", "myclient");
AccessTokenResponse t = k.tokenManager().getAccessToken();
logger.info(t.getSessionState());
logger.info(t.getToken());
}
Unfortunatly both the session_state and token is NULL.
All the data are correct, the url,the realm..etc. Otherwise we would know about that. Keycloak doesnt log anything just silently returns null.
On the top of that I can use the above code from anywhere else and it works! I can use it from a plain java main() method and still works. Getting token by hand via postman also works.
What is wrong with the Keycloak Provider? How can I get an accesstoken for a particular user?
You can use the following example to create a AccessToken:
public String getAccessToken(UserModel userModel, KeycloakSession keycloakSession) {
KeycloakContext keycloakContext = keycloakSession.getContext();
AccessToken token = new AccessToken();
token.subject(userModel.getId());
token.issuer(Urls.realmIssuer(keycloakContext.getUri().getBaseUri(), keycloakContext.getRealm().getName()));
token.issuedNow();
token.expiration((int) (token.getIat() + 60L)); //Lifetime of 60 seconds
KeyWrapper key = keycloakSession.keys().getActiveKey(keycloakContext.getRealm(), KeyUse.SIG, "RS256");
return new JWSBuilder().kid(key.getKid()).type("JWT").jsonContent(token).sign(new AsymmetricSignatureSignerContext(key));
}
Note that you also need to specify <module name="org.keycloak.keycloak-services"/> in your jboss-deployment-structure.

How to create temporary URL for Swift object storage using REST API?

Swift Object storage allow you to create a temporary URL for any resource with an expiry date. This can be achieved with swift CLI command line. To make use of this functionality in an web application, I need to achieve the creation of temporary URL using API call, So that I can make a rest CALL and get the temp URL which can later be embedded in HTML and resource downloaded by the we browser directly.
From the documentation I dont see any API mentioned for this ? Do anyone know how i can get it from Java using API call.
Thanks
Manoj
There is no direct API available to generate temporary URL for Swift objects. Instead it has to generated from client side with the help of X-Account-Meta-Temp-URL-Key secret key as per described in this document
Here is the python version of code to generate it. Refer this to re-implement it in Java and then it can be embedded anywhere.
import hmac
from hashlib import sha1
from time import time
method = 'GET'
duration_in_seconds = 60*60*24
expires = int(time() + duration_in_seconds)
path = '/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30/container/object'
key = 'mykey'
hmac_body = '%s\n%s\n%s' % (method, expires, path)
sig = hmac.new(key, hmac_body, sha1).hexdigest()
s = 'https://{host}/{path}?temp_url_sig={sig}&temp_url_expires={expires}'
url = s.format(host='swift-cluster.example.com', path=path, sig=sig, expires=expires)
Here is an another reference, which is a customization done to Openstack Horizon to provide an UI feature to generate swift objects temp URL.
For other people looking for the answer in java, Below is the code snippet to get the hmac in java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private static String toHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}
public static String calculateRFC2104HMAC(String data, String key)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
return toHexString(mac.doFinal(data.getBytes()));
}
The above code is taken from https://gist.github.com/ishikawa/88599
Use the hmac to create the temporary URL as per the below code
Long expires = (System.currentTimeMillis()/1000)+ <expiry in seconds>;
String tempURL=""+baseURL+path+"?temp_url_sig="+hmac+"& temp_url_expires="+expires;
Thanks

Mongodb authentication using MongoCredential

I have a grails application in which Im using db.authenticate for a login page but I understand this method has been deprecated and therefore I would like to upgrade my application to using the MongoCredential object for authentication. However, unlike the db.authenticate which nicely returns a boolean to get authentication done, the MongoCredential doesn't return a boolean so how can I go about accomplishing the code replacement with minimal headache. Ideally, I'd like to derive some kind of a boolean to tell me if authentication was achieved. Thanks for your patience. Im a newbie with Mongodb.
This is part of the code I need to replace which currently makes use of the deprecated method "authenticate":
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("twcdb");
def userName = params.username
def passWord = params.password
//deprecated method being used in the line below.
boolean auth = db.authenticate(userName, passWord.toCharArray())
if (auth) {
userloggedin = params.username
render(contentType: 'text/json') {
[success: true, url: createLink(controller: 'admin', action: 'loggedin')]
}
}
else {
render(contentType: 'text/json') {
["success": false, "message": 'Login or Password is incorrect.']
}
Edit: I know that the answer must lie in testing a property of the MongoClient object somehow to see if it contains a valid authenticated connection but I am still stuck on how to do this. Given I knowingly feed the MongoClient constructor with a bogus MongoCredential, it still creates an object that isn't null. I was betting on the null test but no joy. So, how do I replace the deprecated db.authenticate?

How to correctly authorize into Mongo server using Scala?

I have added authorization to my Mongo database and now I can't perform any queries whats so ever.
Every time I try I get:
reactivemongo.core.commands.DefaultCommandError: BSONCommandError['command failed because the 'ok' field is missing or equals 0'] with original doc {
ok: BSONDouble(0.0),
errmsg: BSONString(unauthorized)
}
And my Authorization bit seams to be alright but it is just not doing the job:
private val driver = new MongoDriver(actorSystem)
private val dbName = "myDatabase"
private val userName = "root"
private val password = "pass"
private val credentials = Seq(Authenticate(dbName, userName, password))
private val connection = driver.connection(List("111.111.111.11"), credentials)
//connection.authenticate(dbName, userName, password)
private val db = connection(dbName)
The user credentials were created
Any ideas on what is wrong here?
Apparently unauthorized means not that I has not logged in it means that the user does not have sufficient permissions or Roles as they are grouped in Mongo.
Some tutorials about adding authorization have skipped that part er go I get to relearn the lesson of reading an official documentation of any resource again...
http://docs.mongodb.org/manual/reference/method/db.addUser/