Add/attach AWS IAM Role to EC2 instance via terraform - amazon-ec2

i have a quick question here..
I am using terraform to deploy ec2 instances on AWS, and i need a way to attach AWS IAM Role to the instance.
I have created manuall on AWS console an IAM Policy + role, and attached to EC2 instance and tested, it works.
Now i need to use same role (i created earlier manually) to automatically attach to new ec2 instances via terraform
I am tring to do this:
resource "aws_instance" "test-ec2" {
ami = "ami-xxxxxxxxxx"
instance_type = "t3.large"
iam_instance_profile = "arn:aws:iam::1234567890:role/my-role-name" ## I know i am missing something here... (:facepalm:)
key_name = "my-key"
subnet_id = "subnet-some-subnet-d"
vpc_security_group_ids = ["sg-some-group-id"]
associate_public_ip_address = true
root_block_device {
delete_on_termination = true
volume_type = "gp3"
volume_size = 40
}
The reason i am doing it that way (create manualy role once and not via terraform) is becouse i dont
want to give terraform ability to create roles and permissions, only ec2 instances and attach only existing
role, less permissions on jenkins/terraform = better security (at least this is what i think is proper..)
Will be glad for any ideas..:)
Thanx alot!

Related

Keycloak HTTP 401 Unauthorized while creating new user using spring boot service

Getting javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized while trying to create new user in keycloak with spring boot service.
In KeycloakConfig class. it is breaking during creating keycloak instance with HTTP 401 Unauthorized. "message": "javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized",
Am I missing anything? I dont have any extra role configuration in the keycloak client or realm role.
I was thinking to add ".authorization(...) in KeycloakBuilder.builder but I'm not sure what to specify.
public static Keycloak getInstance(User user) {
if (keycloak == null) {
keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/auth")
.realm("myrealm")
.username(user.getUsername()).password(user.getPassword())
.grantType(OAuth2Constants.PASSWORD)
.clientId("myclient")
.clientSecret("0a53569564d2a748a0a5482699")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();
}
return keycloak;
}
In service class
UsersResource usersResource = KeycloakConfig.getInstance(user).realm("myrealm").users();
CredentialRepresentation credentialRepresentation = createPasswordCredentials(user.getPassword());
UserRepresentation kcUser = new UserRepresentation();
kcUser.setUsername(user.getEmail());
kcUser.setCredentials(Collections.singletonList(credentialRepresentation));
kcUser.setFirstName(user.getFirstName());
kcUser.setLastName(user.getLastName());
kcUser.setEmail(user.getEmail());
kcUser.setEnabled(true);
kcUser.setEmailVerified(false);
javax.ws.rs.core.Response response = usersResource.create(kcUser);
System.out.println("kcUser: " + kcUser.toString());
System.out.printf("Repsonse: %s %s%n", response.getStatus(), response.getStatusInfo());
in properties file
keycloak.realm=myrealm
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.resource=myclient
keycloak.credentials.secret=0a5356444d26a748a0a5482699
keycloak.ssl-required= external
keycloak.use-resource-role-mappings= true
keycloak.bearer-only=true
keycloak.principal-attribute=preferred_username
Due to missing imports I assume that KeycloakBuilder is comming from package org.keycloak.admin.client.KeycloakBuilder
Based on your provided code examples you are trying to instantiate a Keycloak instance with an user you just want to create. That user is lack of the privileges to create a new user.
That said you need to create an Keycloak instance with an user that has admin rights / roles. At least "manage-users, view-clients, view-realm, view-users"
keycloak = KeycloakBuilder.builder()
.serverUrl(KEYCLOAK_SERVER_URL)
.realm("master")
.clientId("admin-cli")
.username("admin")
.password("admin")
.build();
With admin access you are able to create users for several realms.
// Create a new user
final UserRepresentation newUser = new UserRepresentation();
newUser.setUsername("username");
newUser.setFirstName("fristname");
newUser.setLastName("lastname");
newUser.setEmail("username#example.com");
newUser.setEnabled(true);
// Now you need to get the realm you want the user to add to and the user ressource
final UserResource realm = keycloak.realm("nameOfTheRealm").users();
// Create the user for the realm
final Response createUserResponse = userRessource.create(newUser);
// check response if everything worked as expected
Make sure the admin account is created under 'myrealm'. You cannot use the default admin account (master realm) to create the user for 'myrealm'
In order for a user to have the right to manipulate and call Keycloak's API, you must set the client role for that user
Step 1: User should create a administrators like "admin" password "abc123" in your client "myrealm"
Step 2: Click admin user after move to Roles mapping tab and assign some necessary permissions to admin user as below
Step 3: Replace password in .username(user.getUsername()).password(user.getPassword()) with "abc123"
Hope to help you!

AWS Lambda Function Timing out while modifying volume

I'm trying to write a simple aws lambda js function that when I pass region, volumeid and volumetype it changes the volume type of the volume with that ID.
Anyway, whenever I try to test the function passing all the parameters, I get the function timing out after 3000ms, but I can't understand why...
Can somebody help me?
Many thanks in advance!
const AWS = require('aws-sdk');
const ec2 = new AWS.EC2({ region: event.instanceRegion });
ec2.ModifyVolume({ VolumeId: [event.volumeId] , VolumeType: [event.VolumeType] });

How to authenticate user with firebase sdk

I am using this SDK and following this documentation. Now I am trying to create and authenticate user in firebase db. How can I do that.I am doing the project in Codeigniter and in my controller I did this:
public function register()
{
$firebase = (new Firebase\Factory())->create();
$tokenHandler = $firebase->getTokenHandler();
$uid = 'a-uid';
$claims = ['foo' => 'bar']; // optional
// Returns a Lcobucci\JWT\Token instance
$customToken = $tokenHandler->createCustomToken($uid, $claims);
echo $customToken; // "eyJ0eXAiOiJKV1..."
$idTokenString = 'eyJhbGciOiJSUzI1...';
// Returns a Lcobucci\JWT\Token instance
$idToken = $tokenHandler->verifyIdToken($idTokenString);
$uid = $idToken->getClaim('sub');
echo $uid; // 'a-uid'
}
and I call the function It gave me this error:
Type: Kreait\Firebase\Exception\ServiceAccountDiscoveryFailed
Message: Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "FIREBASE_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "GOOGLE_APPLICATION_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromGoogleWellKnownFile: The well known file is not readable or invalid
Filename: E:\xampp\htdocs\firebasedb\vendor\kreait\firebase-
php\src\Firebase\ServiceAccount\Discoverer.php
Line Number: 48
Can anyone help me with this issue? Any kind of help are appreciated. Thanks.
EDIT
Okay I solve this problem with default .json file path like this:
$serviceAccount = ServiceAccount::fromJsonFile(JSON_FILE_PATH.'google-service-account.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
Now can I register a new user from web-app? Can anyone Help please. I have been stopped in this problem since long. Helps are highly appreciated.
You Set JSON Key environment variables
FIREBASE_CREDENTIALS GOOGLE_APPLICATION_CREDENTIALS ?
try reading this Firebase Admin SDK for PHP Setup
From the documentation https://firebase-php.readthedocs.io/en/latest/authentication.html#authenticate-with-admin-privileges
There two crucial points to note.
Many use cases for verifying ID tokens on the server can be accomplished by using Security Rules for the Firebase Realtime Database and Cloud Storage. See if those solve your problem before verifying ID tokens yourself.
The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs Check out https://firebase.google.com/docs/auth/users/#auth_tokens
About Users:
From https://firebase-php.readthedocs.io/en/latest/user-management.html
You have a sample
$request = \Kreait\Auth\Request\CreateUser::new()
->withUnverifiedEmail('user#example.com')
->withPhoneNumber('+15555550100')
->withClearTextPassword('secretPassword')
->withDisplayName('John Doe')
->withPhotoUrl('http://www.example.com/12345678/photo.png');
$createdUser = $auth->createUser($request);
Please Note:
By default, Firebase Authentication will generate a random uid for the new user. If you instead want to specify your own uid for the new user, you can include in the properties passed to the user creation method:
$properties = [
'uid' => 'some-uid',
// other properties
];
$request = \Kreait\Auth\Request\CreateUser::new()
->withUid('some-uid')
// with other properties
;
I had same problem with Laravel in my case, here is the solution:
First save the .json credentials file you got from Firebase project into the root of your Laravel app on the same level as .env file.
The json file looks like you-file-firebase-adminsdk-0000-9845985498a.json
Then open the .env file and create a new environment variable and paste the json credential file name.
FIREBASE_CREDENTIALS=../you-file-firebase-adminsdk-0000-9845985498a.json

Parse.com update Role error

I'm getting {"code":101,"error":"object not found for update"} when calling save on my role after adding a user to it, all on Cloud Code.
Sample code:
var role_query = new Parse.Query('_Role')
role_query.equalTo('name', 'USER')
role_query.first().then(function(role) {
role.getUsers().add(user)
role.save()
})
The error was that I didn't have permission to update the role.
Solution was using Parse.Cloud.useMasterKey() at the beginning of the Cloud Code function.
In case you need to update roles on the client:
https://www.parse.com/questions/role-cant-assign-user-in-js

ASP.NET Authorize attribute and Admin user role

Using Authorize attribute i may specify roles which is allowed to access the resources.
[Authorize(Roles="User")]
But if i have admin user which is allowed to go to any resource i need specify this one as well
[Authorize(Roles="User, Administrator")]
But may be there is some way i can say somehow that Administrator allowed to go anywhere and not to specify this one in Authorize attribute?
So i mean if somewhere in code(on controller or on action) would be this [Authorize(Roles="User")] it means that Administrator role allowed to go there as well.
Or may be i may set it to all Authorize roles dynamically how when application start?
Any ideas?
UPDATED:
Currently i have one admin controller with Authorize attribute [Authorize(Role="Administrator")] and i have some actions in some another controllers with attributes [Authorize(Role="User")] so i will need to add "Administrator" there as well if i didn't find better solution.
I think this will work for you. Create your own base controller, with the AuthorizeAttribute, then make your other Controllers inherit your base class.
[Authorize(Roles="Admin")]
public class MyFancyController : Controller
{
}
[Authorize(Roles = "TaxPayer")]
public class WizardController : MyFancyController
{
...
This is scary though, in my opinion.
How many controllers/Actions do you have? What if you forget about this later and maybe you have a page you don't want Admins to access?
Will debugging the code become more difficult?
[Authorize(Roles = "User, Admin")]
public class PrestamosController : Controller
{
// controller details
}
You can create a custom filter and use it to decorate your Actions or Controllers with it.
This is a simple structure I've used quite a lot:
public class AuthorizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
return;
}
var actionName = filterContext.ActionDescriptor.ActionName;
var controllerName = filterContext.Controller.GetType().Name;
bool isAuthorized =false;
// Put your logic here !!!!
if (!isAuthorized) {
filterContext.Result = new HttpUnauthorizedResult();
return;
}
}
}
You can read some more here
This is what I do: make sure users who are in the "Admin" role are also in the "User" role.
You need the concept of Static Role and Runtime Role. Here is a simple example:
Your role list and their levels:
Role: Admin | Level: 1
Role: Editor | Level: 2
Role: Viewer | Level: 3
Users and their Static Role (Static Role is the role you assigned to users):
User: John | Role: Admin
User: Sam | Role: Editor
User: Peter | Role: Viewer
At run time you generate a Run Time Role by using Static Role and Role Levels, Users with higher level of roles automatically obtain the roles in lower levels. So, after calculation, the Run Time Roles for these Users will be:
User: John | Role: Admin, Editor, Viewer
User: Sam | Role: Editor, Viewer
User: Peter | Role: Viewer
And then, you can simply use [Authorize(Roles="Viewer")], Users with higher Level of permissions (e.g. John, Sam) can access to it too. Because they must also have the Viewer role at run time.
The point of using Static Role and Run Time Role is that Static Role makes the role assignment easier. And Run time role make the resources authorization easier.

Resources