Hi I'm using Keycloak and I would like to know what is the best way to get Users in Client Role. Is there a Keycloak API to get this?
I can get user role details with jwt token. But I need to get all users under a client role
I'm not familiar with English. Thank you for your understanding.
Grant the client role to a user
Get representation of the client
## If you know the uid of the client, you don't need it.
## If you don't know the client's uid, you can get it with this.
GET /{realm}/clients?clientId={client-name}
Get a role by name
GET /{realm}/clients/{client-uid}/roles/{role-name}
Get all roles for the realm or client
GET /{realm}/clients/{client-uid}/roles
Get a role by name
GET /{realm}/clients/{id}/roles/{role-name}
# python example
url = "{}/auth/admin/realms/{}/clients/{}/roles?".format(kc_url, kc_realm, client_uid)
headers = {
'Authorization': 'bearer {}'.format(token)
}
response = requests.request("GET", url, headers=headers).json()
Add client-level roles to the user role mapping
## Add the information you got from the role name to the body.
POST /{realm}/users/{id}/role-mappings/clients/{client-uid}
# python example
url = "{}/auth/admin/realms/{}/users/{}/role-mappings/clients/{}".format(kc_url, kc_realm, user_uid, client_uid)
list = []
list.append(role_info)
payload = json.dumps(list)
headers = {
'Authorization': 'bearer {}'.format(token),
'Content-Type': 'application/json',
}
response = requests.request("POST", url, headers=headers, data=payload)
Get a list of users who have been granted the client role
Returns a stream of users that have the specified role name.
GET /{realm}/clients/{id}/roles/{role-name}/users
See the documentation for more APIs.
You can also grant a client role when creating a user.
Adding the client role to the group and adding the user to the group is also a way.
Related
Bothering again but really need a piece of advice from the community
Imagine I have 3 user types:
read
write
admin
with different permissions and I need to request a token for all 3. Then store each token and then be able to run some tests for read user, other tests for admin and some tests for all 3 profiles.
Is it possible to handle with Karate?
I know there is ScenarioOutline but that would require me to add this ScenarioOutline to every single scenario.
Also thought about having a json.file and run my CreateToken.feature with every single user that is in this users.json but then I don't know how to tell my tests which token to use.
My Create Token feature file for the basic profile is:
Feature: Create Token
Background: URL definition
* url authUrl
Scenario: Create Token for Read user
When path '/v2/u/login'
And request
"""
{
"username": "#(readUser)",
"password": "#(password)"
}
"""
And method Post
Then status 200
* def readAccessToken = response.token
in karate-config.js I have defined the 3 users:
var config = {
readUser: 'readuser#example.com',
writeUser: 'writeuser#example.com',
adminUser: 'adminuser#example.com',
password: karate.properties['password'],
}
const readAccessToken = karate.callSingle('classpath:helpers/CreateToken.feature', config).readAuthToken
karate.configure('headers', {Authorization: 'Bearer ' + readAccessToken})
In the Feature files:
Scenario: Get explore page
#This should run for all 3 types of users
When path '/a/v2/explore'
And method Get
Then status 200
And match response contains exploreResponse
Scenario: Get user list
#This should run only for admin user
When path '/users'
And method Get
Then status 200
Sorry but I can't the best way to setup this
Thanks!
I would just create the 3 tokens using call-single, keep them as global variables in config and then use them the way you see fit.
I am trying to create an Express API with JWT authentication.
However, I was wondering how to best allow users to only access their own resources.
For example if there is a user with id 1 and each user has a list of books in the database:
The id is already part of the JWT Token but commonly there would be a request to something like /users/1/books to get all of the books belonging to user 1.
Would my routes typically still look like this and I would just check the id in the token is the same the request is made for, or is there any other/simpler way?
Thank you for your help!
You can define, some access rights permissions base on the user role or id.
Example: roles : {root, admin, staff}
Then, in your routes you can have some checking whether this user have the permission to access the functions or you can do in the controller level to check the access rights.
You need to define model relations between User, UserModel. In your case as I understand you need to have the relations between UserModel and BooksModels.
UserModel hasMany BooksModel
When you call findOne() to retrieve specific user's data, you can just define include: 'aliasModelName', to retrieve the users related book data.
With this way, you can only have 1endpoint users/:id to retrieve users data and book data. It depends on what you really want, you can also have an endpoint users/:id/books to get all books that belongs to this user.
Your model definition will then become
BooksModel belongsTo UserModel
If you use hasMany you can get all the results that you need in just one query.
Hope this helps!
When user sends the login credentials, you check database if the email exists, if yes then you check if the password matches. If user successfully signins you create the token.
const token = jwt.sign({ _id: user._id, email: user.email }, "this-is-secret", {
expiresIn: "1h",
});
this token is sent to the browser, whenever user make requests, it manually attachs this token to the req, and sends the request to your server. You check if the token is valid, by using the secret key (in this case "this-is-secret").
const decodedToken = jwt.verify(token, "this-is-secret")
req.userId = decodedToken.userId;
now "userId" is attached to the req object. Now when you fetch the data from database, the items that you are fetching, you write a query that (implementation depends on which database you are using)
book.userId=req.userId
If I open someone's Google Plus Profile Page I see contact info and information shared on Google Plus. I looking for similar information on Google API. I'm trying to fetch list of user's contacts with email and google plus profile id, that's all.
Here I can fetch user connections with Google Plus profile url but without email or phone number.
https://people.googleapis.com/v1/people/me/connections
Here I can fetch person contacts with email and phone number (OAuth2) - without Google Plus profile url nor id
https://www.google.com/m8/feeds/contacts/{GOOGLE_ACCOUNT_NAME}%40gmail.com/full?alt=json
But I don't know how to combine this two outputs, to get have Google Plus profile url and contact information.
You are correct. To retrieve profile information for a user, use the people.get API method. To get profile information for the currently authorized user, use the userId value of me.
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log('Retrieved profile for:' + resp.displayName);
});
});
Note that this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me.
Plus.People.List listPeople = plus.people().list(
"me", "visible");
listPeople.setMaxResults(5L);
PeopleFeed peopleFeed = listPeople.execute();
List<Person> people = peopleFeed.getItems();
// Loop through until we arrive at an empty page
while (people != null) {
for (Person person : people) {
System.out.println(person.getDisplayName());
}
// We will know we are on the last page when the next page token is
// null.
// If this is the case, break.
if (peopleFeed.getNextPageToken() == null) {
break;
}
// Prepare the next page of results
listPeople.setPageToken(peopleFeed.getNextPageToken());
// Execute and process the next page request
peopleFeed = listPeople.execute();
people = peopleFeed.getItems();
}
Here's a related SO ticket which discuss how to fetch user email from Google+ Oauth: How to get user email from google plus oauth
You can use the Google Api to fetch the user profile. For this
Create project in google api console.Configure the credentials client id,client secret. Add your redirect uri.
Authorize the user with OAuth2.0 from your project with scopes https://www.googleapis.com/auth/plus.me , https://www.googleapis.com/auth/plus.login.
Retrieve the response code after authorization.Give POST method to the token endpoint url.
Retrieve the access_token, refresh_token,id_token etc from gooogle plus.
By using the access_token. call GET method to the url "https://www.googleapis.com/plus/v1/people/me/?access_token='{YOUR_ACCESS_TOKEN}'".
You will be given by an json array containing the authorized user profile details like email, name, id etc.
I developed a program which works well and I can import data from gmail but. I want to keep track how is the user given permission to manage contacts. But after a hard search I did not get any Idea about the loged in user. My code is as follows.
============================================
var parameters = new OAuth2Parameters
{
ClientId = ConfigurationManager.AppSettings["ClientID"].ToString(),
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString(),
RedirectUri = ConfigurationManager.AppSettings["RedirectURL"].ToString(),
Scope ="https://www.googleapis.com/auth/userinfo.profile"
};
parameters.AccessCode = Request.QueryString["Code"].ToString();
OAuthUtil.GetAccessToken(parameters);
Session["Token"] = parameters.AccessToken;
==================================
But I dont how to get email of logged in user. Please let me that
Thanks in advance
Request an additionall scope of https://www.googleapis.com/auth/userinfo.email and then you can access the user info as well. There is also a userinfo.profile witch contains other info on the user like name, profile picture, language and so on.
Your code looks like C# but I only have a Python example of using multiple scopes and sharing tokens.
Code: https://code.google.com/p/google-api-oauth-demo/
Article: http://www.hackviking.com/2013/10/python-get-user-info-after-oauth/
My application gets approved and a user gets an access token and extended permissions which include offline_access and publish_stream.
I want to be able to post from inside my model. This would require me to make an
https://graph.facebook.com/FBUSER_ID/feed
plus some parameters and access token, app_id, app_secret.
I have the access token and FBUSER_ID.
What I don't know how to do is put it all together in the model.
Could anyone point me in the right direction?
I already have a facebook application. I need to know how to post from the server to a users wall
**Thanks to the answer below I was able to get it working with the following:
access_token = "AAACvmqy1nYoBAAZCkGXbVgRwcBv******ZAMjsLxKxR7DaZBE0NxY8ZBGBW1q2mzsB9TDT0RvgeQcDdnyFJNAYRf0icnhlbikZD"
appID = '1776938807888574888888888882'
message = 'test_message'
userID = '75164088804088888'
uri = URI.parse("https://graph.facebook.com/#{userID}/feed")
req = Net::HTTP::Post.new(uri.path)
result = req.set_form_data({:access_token => access_token , :message => message, :app_id => appID })
sock = Net::HTTP.new(uri.host, 443)
sock.use_ssl = true
sock.start do |http|
response = http.request(req)
end
IMPORTANT: at the top of the controller or model add:
require 'openssl'
First you have to create a Facebook application here. By the app_id and app_secret of created application, you will ask user to give "publishing feed" permission to your application. While getting this permissions you get also the access token for posting the users wall.
You can get detailed info about authentication here:
https://developers.facebook.com/docs/authentication/
And you can get info about publishing here on the Publishing section:
http://developers.facebook.com/docs/reference/api/
With ruby, your need is just making an HTTP Post. This may be an example for this:
Net::HTTP.post_form(URI.parse('https://graph.facebook.com/FBUSER_ID/feed'),
{'access_token' => 'ACCESS_TOKEN', 'message' => 'MESSAGE'})