I'm trying to authenticate a user with password like this:
let syncCredentials = SyncCredentials.usernamePassword(username: email, password: password, register: true)
SyncUser.logIn(with: syncCredentials, server: Constants.Realm.Server) { (realmUser, error) in
guard let realmUser = realmUser else {
DDLogError("\(error)")
return
}
DDLogInfo("realmUser: \(realmUser)")
}
but it prints out this error:
Optional(Error Domain=io.realm.sync Code=611 "The provided credentials are invalid." UserInfo={statusCode=400, NSLocalizedDescription=The provided credentials are invalid.})
The Server constant is correct, as I can successfully connect to the Realm Object Server using Facebook credentials.
You can get this error if you register the user that already exists, so specify register: false if the user is already registered.
Related
Recently I integrated superset with my web application so that when an user who is authenticated by my web application can enter superset and view/edit/create dashboards based on their role just by clicking the link no need to even login. For doing this I had to bypass the login for which I referred this article.
Custom SecurityManager I used to bypass login
class CustomAuthDBView(AuthDBView):
#expose('/login/', methods=['GET', 'POST'])
def login(self):
redirect_url = self.appbuilder.get_url_for_index
user_name = request.args.get('username')
user_role = request.args.get('role')
if user_name is not None:
user = self.appbuilder.sm.find_user(username=user_name)
if not user:
role = self.appbuilder.sm.find_role(user_role)
user = self.appbuilder.sm.add_user(user_name, user_name, 'last_name', user_name + "#domain.com", role, password = "password")
if user:
login_user(user, remember=False)
return redirect(redirect_url)
else:
print('Unable to auto login', 'warning')
return super(CustomAuthDBView,self).login()
class CustomSecurityManager(SupersetSecurityManager):
authdbview = CustomAuthDBView
def __init__(self, appbuilder):
super(CustomSecurityManager, self).__init__(appbuilder)
So according to above code using url http://localhost:8088/login?username=John will login the user John internally or if user John does not exist account is created with some role which is based on the role of user in my web application
Now the problem is anyone who can guess this url http://localhost:8088/login?username=USER_NAME can create their account in superset, so how to protect or secure this '/login' endpoint
You can use the API so that you dont expose request details over the URL.
from flask_appbuilder.api import BaseApi, expose
from . import appbuilder
class LoginApi(BaseApi):
resource_name = "login"
#expose('/loginapi/', methods=['GET','POST'])
##has_access
def loginapi(self):
if request.method == 'POST':
username = request.json['username']
password = request.json['password']
appbuilder.add_api(LoginApi)
What I'm doing?
I'm working on a iOS app which is going to download files from an FTPS server. For this purpose I'm using the library FilesProvider.
Error description
Until now I successfully achieve to login in the server, list files and search for files, but I'm getting the following error when trying to download one of the files:
File Provider <FilesProvider.FTPFileProvider: 0x283c23900> shouldDoOperation Copy with action Copying and destination file:///private/var/mobile/Containers/Data/Application/90AF4202-18C1-4A41-B461-4FB262FD39B9/tmp/B13A8110-C919-48E4-8BD9-E684929310C0.tmp
2020-05-27 14:35:39.372289+0200 MyApp[548:100799] [] nw_socket_handle_socket_event [C13:1] Socket SO_ERROR [54: Connection reset by peer]
2020-05-27 14:35:39.595959+0200 MyApp[548:99892] CFNetwork SSLHandshake failed (-9806)
2020-05-27 14:35:39.596380+0200 MyApp[548:99892] TCP Conn 0x28274f540 SSLHandshake failed (-9806)
File Provider <FilesProvider.FTPFileProvider: 0x283c23900> Failed for operation Copy with action Copying and destination file:///private/var/mobile/Containers/Data/Application/90AF4202-18C1-4A41-B461-4FB262FD39B9/tmp/B13A8110-C919-48E4-8BD9-E684929310C0.tmp
Throwing Error: Error Domain=NSOSStatusErrorDomain Code=-9806 "(null)" UserInfo={_kCFStreamErrorCodeKey=-9806, _kCFStreamErrorDomainKey=3}
FTPFileProvider is an object created with the library I've mention above that handles the FTP connection. That provider looks like:
guard let url = URL(string: "ftps://X.X.X.X") else { return } // I have to use an IP address instead of a domain
var provider = FTPFileProvider(baseURL: url, mode: .default, credential: credential, cache: .none)
provider.delegate = self
provider.fileOperationDelegate = self // This delegate is only for print the first line of the error
provider.serverTrustPolicy = .disableEvaluation
After creating the provider of the connection, I've been able to do login in the server, search some files and get the file list. I'm doing that with this function:
provider.searchFiles(path: remotePath, recursive: false, query: predicate, foundItemHandler: { (file) in print("File found with name: \(file.name)") }, completionHandler: { (list, error) in
if error != nil {
DispatchQueue.main.async {
onError(error!)
}
} else {
var files:[String] = []
for f in list {
(f.isRegularFile) ? files.append(f.name) : nil
}
DispatchQueue.main.async {
onSucess(files)
}
}
})
When running that search I get this warning:
2020-05-27 14:45:51.831812+0200 MyApp[555:102153] [] nw_socket_handle_socket_event [C4:1] Socket SO_ERROR [54: Connection reset by peer]
But I successfully get an output in onSuccess(files). The returned value for files is:
["20200527-093234-28346646454.pdf", "20200527-105409-28346646454.pdf"]
After that search, I try to download one of the files is when I get the error describe at the beginning of this post. For do the download I have the following function:
provider.copyItem(path: "\(remotePath)/\(file)", to: localPath.absoluteString, overwrite: true) { (error) in
if error != nil {
DispatchQueue.main.async {
onError(error!)
}
} else {
DispatchQueue.main.async {
onSuccess(localPath)
}
}
}
What I've try
As you could see above, the object who connect to the server has disabled the SSL certificate checks. That's why I can do the login and search for the files.
I've configure the Info.plist disabling ATS:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key> <!-- Because I wan't to allow everything -->
<true/>
<key>NSAllowsLocalNetworking</key> <!-- Because seems like library uses AVFoundation framework -->
<true/>
<key>NSAllowsArbitraryLoadsForMedia</key> <!-- Because I'm using a public IP instead a domain -->
<true/>
</dict>
Neither of that options works.
Some facts
Domain DNS entry is not going to be created for now. I can't do anything about this.
Server do have a valid SSL certificate.
I can successfully login, list files and search for files. (I just can't download)
I didn't try to upload a file. App isn't going to do it.
Questions
Why login, listing or searching files works but I get that error when trying to download?
Any idea on how to fix it? Any workaround?
I'm working with keycloak 8.0.1 and it's java client keycloak-admin-client library.
this is my Keycloak config
public Keycloak keycloakClient(AdapterConfig config) {
return KeycloakBuilder.builder()
.clientId(config.getResource())
.clientSecret((String) config.getCredentials().get(CredentialRepresentation.SECRET))
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.realm(config.getRealm())
.serverUrl(config.getAuthServerUrl())
.build();
}
And with this code I'd like to create user and assign him a role
final UserRepresentation user = createUserRepresentation(data);
final UsersResource userResource = getRealmResource().users();
try (Response response = userResource.create(user)) {
if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
final String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
final RolesResource rolesResource = getRealmResource().roles();
final RoleResource roleResource = rolesResource.get(data.getRole().getRemoteName());
final RoleRepresentation role = roleResource.toRepresentation();
userResource.get(userId).roles().realmLevel().add(Collections.singletonList(role));
return userId;
} else {
throw new IllegalStateException("Unable to create user " + response.getStatusInfo().getReasonPhrase());
}
}
however it fails on line final RoleRepresentation role = roleResource.toRepresentation(); with message javax.ws.rs.ForbiddenException: HTTP 403 Forbidden.
I don't understand why am I getting this error, because my client has assigned all roles from realm-management client
create-client
impersonation
manage-authorization
manage-clients
manage-events
manage-identity-providers
manage-realm
manage-users
query-clients
query-groups
query-realms
query-users
realm-admin
view-authorization
view-clients
view-events
view-identity-providers
view-realm
view-users
Is there some config which am I missing or is it a bug?
Thanks
I just have the same problem here, while I'm trying to assign roles to an existing user using a service client (using client credentials).
The solution:
Go to Clients > Select "your" client > Go to "Service Account Roles" Tab > Select Client Roles : "realm-management" and add "view-realm" into the assigned roles.
That's it :)
I am having trouble getting access to the users Apple Music.
The error I am getting is
[core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2019-02-04 19:14:37.250467+0900 SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
2019-02-04 19:14:37.252008+0900 [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2019-02-04 19:14:37.252051+0900 SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
2019-02-04 19:14:37.253604+0900 SSAccountStore: Unable to get the local account. error = Error Domain=SSErrorDomain Code=100 "Cannot connect to iTunes Store" UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}
However the weird part of this code is that I am also able to retrieve the Music User Token.
Is there sth that I am missing?
Any help is appreciated.
static func auth(){
let cloudServiceController = SKCloudServiceController()
let developerToken = "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz"
SKCloudServiceController.requestAuthorization { status in
guard status == .authorized else { return }
}
cloudServiceController.requestCapabilities { capabilities, error in
guard capabilities.contains(.musicCatalogPlayback) else { return }
}
cloudServiceController.requestUserToken(forDeveloperToken: developerToken, completionHandler: { token, error in
guard let token = token else { return }
UserDefaults.standard.set(token, forKey: "MUSIC_USER_TOKEN")
UserDefaults.standard.set(developerToken, forKey: "DEVELOPER_TOKEN")
print("Music User Token:", token)
})
}
I think you have to call
cloudServiceController.requestUserToken
once user has authorised after completion handler for SKCloudServiceController.requestAuthorization
I was having this same issue until I removed Bearer from the beginning of developerToken.
OP's code example has developerToken set to "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz", so I can only assume if OP is including Bearer at the beginning or not.
So to be more clear, this is what I was doing before:
asyncAskMyServerToGenerateMyAppleMusicDeveloperJWTDevToken { rawDevToken in
let formattedDeveloperToken = "Bearer \(rawDevToken)"
SKCloudServiceController().requestUserToken(forDeveloperToken: formattedDeveloperToken)
{ possibleToken, _ in
if let userMusicToken = possibleToken
{
YayIGotIt.forTheWin(userMusicToken)
}
}
}
And this is what I did to make it actually work:
asyncAskMyServerToGenerateMyAppleMusicDeveloperJWTDevToken { rawDevToken in
//Not prepending "Bearer " anymore
SKCloudServiceController().requestUserToken(forDeveloperToken: rawDevToken)
{ possibleToken, _ in
if let userMusicToken = possibleToken
{
YayIGotIt.forTheWin(userMusicToken) //This actually fires now
}
}
}
I'm implementing FireAuth error codes for firebase email and password signup, they all work except in 2 cases. When the email address field is empty, case .errorCodeInvalidEmail is called. When i type some letters (no valid email address), the default case is called. For the password field, it's the other way around. When i type one character the case .ErrorCodeWeakPassword" is called. When i leave the field empty, i go to the default case.
this is my code:
#IBAction func SignInButtonPressed(_ sender: LogInVcButton) {
if let email = emailField.text, let password = pwdField.text {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
print("Email User Authenticated with Firebase")
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthErrorCode(rawValue: (error?._code)!) {
switch errCode {
case .errorCodeEmailAlreadyInUse: self.errorMessage(message: "Email address is already in use")
case .errorCodeInvalidEmail: self.errorMessage(message: "Email address is invalid")
case .errorCodeWrongPassword: self.errorMessage(message: "Wrong password")
case .errorCodeWeakPassword: self.errorMessage(message: "Password needs to be minimum 6 characters")
// TODO: A case for if the password field is blank
default: print("default")
}
} else {
print("Successfully Authenticated with Firebase")
}
}
})
}
})
}
}
I don't see which error code would handle the wrong email format or the empty password field in the docs. I can try to handle them my own, but i would think firebase would cover these cases ? https://firebase.google.com/docs/auth/ios/errors
Anyone can help me out ?
edit: after digging in some deeper i managed to print out the firebase descriptions of the errors.
if i pres sign in with emailAddress and password empty:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
case .errorCodeInvalidEmail is called. this is ok
When i write an invalid email address and empty password empty i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK .errorCodeInternalError: It says missing password, but it should check the email address
When i type an invalid email address and one character in the password field i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
This seems ok
when i type a valid email address and no password:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK. .errorCodeInternalError
when i type a valid email address and one character in the pw field
Optional(Error Domain=FIRAuthErrorDomain Code=17026 "The password must be 6 characters long or more." UserInfo={NSLocalizedDescription=The password must be 6 characters long or more., error_name=ERROR_WEAK_PASSWORD, NSLocalizedFailureReason=Password should be at least 6 characters})
.errorCodeWeakPassword is called. This is ok too. and should also be the case on point 5 imo
When i type no email and a valid password
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x600000053ce0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_EMAIL";
reason = invalid;
}
);
message = "MISSING_EMAIL";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK Internal Error is called. Why not same as in point 1 ?