I have 2 possible realms to authenticate my users in my webapplication.
here are a few lines from my shiro.ini:
securityManager.realms = $ldapRealm, $saltedJdbcRealm
strategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $strategy
Authentication works fine for both realms and the FirstSuccessfulStrategy works fine as well.
In my custom AuthenticationFilter within the executeLogin() method I have this code to do the login:
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
currentUser.login(token);
How can I now determine which realm was resposible for the authentication after the .login() method is executed?
If the user was authenticated via the LDAP Realm I would like to get some more information about the user from the LDAP.
Does anyone know how this can be done?
Subject subj = SecurityUtils.getSubject()
SimplePrincipalCollection spc = (SimplePrincipalCollection) subj.getPrincipals();
Set<String> realmNames = spc.getRealmNames();
The realmNames variable should contain one element, the realm that authenticated the user.
If your realm implementation is a standard one then the SimpleAuthenticationInfo created when the user is authenticated will have been created with the name of the realm that successfully authenticated the user.
Related
I'm migrating my ServiceStack Ormite MVC application to use the JWTAuthProvider for stateless auth. I have this working by authenticating as normal, and setting the returned BearerToken and RefreshToken on a successful auth:
using (var authService = HostContext.ResolveService<AuthenticateService>(ServiceStackRequest))
{
var response = await authService.PostAsync(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = model.UserName,
Password = model.Password,
RememberMe = true,
});
var authResponse = response.GetDto() as AuthenticateResponse;
Response.Cookies.Append("ss-tok", authResponse.BearerToken, new CookieOptions() {...});
Response.Cookies.Append("ss-reftok", authResponse.RefreshToken, new CookieOptions() {...});
}
This appears to work for some users and not for others. The problem seems to be that user accounts with a lot of permissions end up with much larger BearerToken values, some over 4096, so these cannot be set for the ss-tok cookie.
The JWT Auth provider docs provide references to the CreatePayloadFilter and the PopulateSessionFilter, however these are only used when creating a session from a token, not the other way around. I want to filter out items (the permissions in particular) when serializing to a token.
Ideally the permissions would be excluded if there are too many (or always be excluded if that's not possible) and would be lazy-loaded when accessed. This may be possible with a custom AuthUserSession inheriting from the base AuthUserSession that Lazy-loads the Permissions, but I don't know how I could do this without the JWT Provider loading the permissions to serialise too.
I'm working on an app that currently uses email/password auth provided by MongoDB Realm. I'm thinking of switching to using the custom JWT auth for various reasons. I'm quite extensively using the custom user data to store all sorts of things. When I switch from email/password to custom JWT the login works, but the custom user data is empty...
This works fine:
const jwt = await axios.post("https://MYAPI.COM/login", {
user: email.value,
password: password.value,
});
console.log(`jwt: ${JSON.stringify(jwt.data)}`);
const credentials = Realm.Credentials.emailPassword(
email.value,
password.value
);
// const credentials = Realm.Credentials.jwt(jwt.data);
console.log("logging in");
const user = await realm.logIn(credentials);
await user.refreshCustomData();
const customUserData = await user.refreshCustomData()
console.log(`Logged in as ${JSON.stringify(user)}`);
console.log(`customUserData: ${JSON.stringify(customUserData)}`);
When I uncomment the line changing the credentials the custom user data is empty
I was running into a similar problem using Custom Function for authentication.
I was mapping the userId incorrectly -
custom user data is based on the ID of the authenticated user, please make sure that the user ID is mapped correctly in the corresponding collection.
https://www.mongodb.com/docs/realm/users/enable-custom-user-data/
I have implemented a custom UserStorageProvider with AbstractUserAdapter for Keycloak for retrieving users from external DB and login users with credentials stored in that DB. All works ok and the data is read only via Keycloak admin panel.
I wanted to add additional attributes to users from data stored in external DB, I would like to add this data to the token via Attribute Mapper, is there a way to do it? Or do II need to implement AbstractUserAdapterFederatedStorage? The problem with the later is that it is not read only and allows to edit the user data transferred to the keycloak user store.
It really depends on your implementation. If you have access to desired data for attributes and to the user, you can simply assign new attributes to him, i.e:
KeycloakSession session = // get session somewhere
RealmModel currentRealm = session.getContext().getRealm();
UserModel user = getUserSomehow(session, currentRealm);
user.setSingleAttribute("attributeName", "attributeValue");
...
private UserModel getUserSomehow(KeycloakSession session, RealmModel realm) {
return KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), "<username>");
// or (cached model):
// return session.users().getUserById("<userId>", realm);
// or (Un-cached model):
// return session.userStorageManager().getUserById("<userId>", realm);
}
I'm trying to get access token for Power BI API. Our account is a federated account.
I've been trying this but it keeps giving me an error saying Incorrect username or password. To use the resource owner password credentials grant flow to get the access token for Azure AD, I make a call to http request diectly using the HttpClient
HttpClient clie = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
var body = "resource=https://analysis.windows.net/powerbi/api&client_id={client_id}&grant_type=password&username={username}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
string result = clie.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
}).Result;
This will work for non federated accounts. How can I implement the same for federated accounts?
The easier would be to leverage MSAL.NET (or ADAL.NET) which does a lot to achieve that. See https://aka.ms/msal-net-up
scopes = new string[]{ "https://analysis.windows.net/powerbi/api/Dashboard.Read.All"}
result = await app.AcquireTokenByUsernamePasswordAsync(scopes, "joe#contoso.com",
securePassword);
Even better if you know that your machine is domain joined or AAD joined, you can use Integrated Windows Authentication: https://aka.ms/msal-net-iwa
result = await app.AcquireTokenByIntegratedWindowsAuthAsync(scopes);
Note that, I recommend using MSAL.NET (instead of ADAM.NET), because with MSAL/NET/the Azure AD v2.0 endpoint, PowerBI offers a better control of the permission scopes:
See the API permissions tab in an app registration in https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
How can i get the rid of the current user (OUser) via the binary api. I am using the inbuilt token based authentication.
I would expect two approaches:
a function like currentUserRID() or something. I looked in the documentation but found nothing.
decrypting the token to unlock the userId/name. I tried this approach but couldn't manage to. I looked here: https://github.com/orientechnologies/orientdb/issues/2229 and also https://groups.google.com/forum/#!topic/orient-database/6sUfSAd4LXo
I find your post just now, may be is too late but you can do like this:
OServer server = OServerMain.create(); // for exemple
ODatabaseDocumentTx db = new ODatabaseDocumentTx(BDDURL).open("admin","admin"); // admin is juste for this exemple
OTokenHandlerImpl handler = new OTokenHandlerImpl(server);
OToken tok = handler.parseWebToken(yourtoken);
OUser user = tok.getUser(db);