Playfab DisplayName is returning null - playfab

I'm trying to log the user in and get the username.
When I try to get username on LoginSuccess() via "InfoResultPayload.PlayerProfile.DisplayName" it's returning null. Here's are the login functions:
public void LoginClick()
{
var login = new LoginWithPlayFabRequest { Username = Username.text, Password = Password.text,
InfoRequestParameters = new GetPlayerCombinedInfoRequestParams { GetPlayerProfile = true }
};
PlayFabClientAPI.LoginWithPlayFab(login, OnLoginSuccess, OnLoginFailure);
}
private void OnLoginSuccess(LoginResult result)
{
//ErrorMessage.text = "";
//SceneManager.LoadScene(SceneName); // Load Main Scene
Debug.Log(Username);
string name = null;
if(result.InfoResultPayload.PlayerProfile != null)
{
name = result.InfoResultPayload.PlayerProfile.DisplayName;
ErrorMessage.text = name;
Debug.Log(name);
}
}
And this is how I registered the user -
public void RegisterClick()
{
var register = new RegisterPlayFabUserRequest { Username = Username.text, Email = Email.text, Password = Password.text };
PlayFabClientAPI.RegisterPlayFabUser(register, OnRegisterSuccess, OnRegisterFailure);
}
private void OnRegisterSuccess(RegisterPlayFabUserResult result)
{
ErrorMessage.text = "";
SceneManager.LoadScene(SceneName); // Load Main Scene
}
Why am I getting "null" when logging in and how can I get the username of the user?

Related

jwt value is null but cookie have value how can I check?

this controller login
[EnableCors("AllowOrigin")]
[HttpPost("login")]
public IActionResult Login(string aimUserMail, string aimUserPassword)
{
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserMail == aimUserMail && x.AimUserPassword == aimUserPassword);
return BadRequest(error: new { message = "UserEmail or password is not correct" });
//}
if (user == null)
{
return BadRequest(error: new { message = "UserEmail or password is not correct ...." });
}
var jwt = this.jwt.Generete(user.AimUserId);
Response.Cookies.Append("jwt",jwt, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
});
return Ok(user);
}
this is controller check auth :
[HttpGet("user")]
public IActionResult User()
{
try
{
var jwt = Request.Cookies["jwt"];
var token = this.jwt.Verify(jwt);
int aimUserId = int.Parse(token.Issuer);
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserId == aimUserId);
return Ok(user);
}
catch (Exception e)
{
return Unauthorized();
}
}
Your jwt is null, seems you have add return method in your login function.
If you want get all cookie, you can try below code. Then you can check what you want.
[HttpGet("GetAllCookie")]
public IActionResult GetCookie()
{
int count = Request.Cookies.Count;
var CookiesArray = Request.Cookies.Keys.ToArray();
List<CookieObj> list = new List<CookieObj>();
CookieObj o;
for (int i = 0; i < count; i++)
{
o = new CookieObj();
string cookieKey = CookiesArray[i];
o.cookiename = cookieKey;
o.cookievalue = Request.Cookies[cookieKey];
list.Add(o);
}
return Ok(list);
}
public class CookieObj {
public string cookiename { get; set; }
public string cookievalue { get; set; }
}

SalesForce: Classic to Lighting

Apologies if my question my be so dumb but my programming skills are really limited and I'm on a hurry for a PoC.
I have the apex class below which was developed for Classic. I would like to make it work with lighting and I'm not sure if the only thing I need to replace are the url's. I have created a developer account for my PoC and everytime I launch the class I'm redirected to Classic.
public class LookupByUrlParamController {
String accountName;
String accountNumber;
String phone;
String website;
String email;
String socialhandle;
public LookupByUrlParamController () { }
public String redirectToAccount() {
Account account;
Map<String,String> params = ApexPages.currentPage().getParameters();
if(params.size() > 0) {
accountName = params.get('account_name');
accountNumber = params.get('account_number');
phone = params.get('phone');
website = params.get('website');
email = params.get('email');
socialhandle = params.get('SocialHandle');
}
try {
if(accountName != null) {
account = [select ID from Account where name = :accountName limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(accountNumber != null) {
account = [select ID from Account where AccountNumber = :accountNumber limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(phone != null) {
String npa;
String nnx;
String extension;
// Added logic for NA phone numbers
if (phone.length() == 10) {
npa = phone.substring(0,3);
nnx = phone.substring(3,6);
extension = phone.substring(6,10);
phone = '(' + npa + ') ' + nnx + '-' + extension;
}
account = [select ID from Account where phone = :phone limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(website != null) {
account = [select ID from Account where website = :website limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(email != null) {
account = [select ID from Account where email__c = :email limit 1];
}
} catch (System.queryException e) {//no entry found for lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
try {
if(socialhandle != null) {
account = [select ID from Account where SocialHandle__c = :socialhandle limit 1];
}
} catch (System.queryException e) {//no entry found for twitter handle lookup item, display empty account page
return 'https://na7.salesforce.com/001/e';
}
String accountUrl;
if(account != null) {
accountUrl = '/' + account.Id;
} else {
accountUrl = '/';
}
return accountUrl;
}
public static testMethod void testLookupByUrlParamAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = 'Avaya';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamInvalidAccount() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountName = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');
}
public static testMethod void testLookupByUrlParamPhone() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParamWherePhoneNumberIs10Chars() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '1234567891';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, 'https://na7.salesforce.com/001/e');//no record found
}
public static testMethod void testLookupByUrlParamInvalidPhoneNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.phone = '';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000015EKVPIA4');
}
public static testMethod void testLookupByUrlParamAccountNumber() {
LookupByUrlParamController controller = new LookupByUrlParamController();
controller.accountNumber = '4321';
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/001A0000007UkkFIAS');
}
public static testMethod void testLookupByUrlParam() {
LookupByUrlParamController controller = new LookupByUrlParamController();
String redirectUrl = controller.redirectToAccount();
System.assertEquals(redirectUrl, '/');
}
}
In addition if anyone can tell where to being looking in the documentation to simply launch to new customer record form, or what are the redirect URLS?
It's not quite clear what you mean by
everytime I launch the class I'm redirected to Classic
However, this code appears not to have been touched in quite a number of years and there's several things you ought to change.
You are hard-coding non-My Domain Salesforce instance URLs (na7.salesforce.com). You should instead use URL.getSalesforceBaseUrl().toExternalForm(), and you'll need to turn on My Domain sooner or later.
You are using Classic-format URLs, which still work but will result in additional redirects. The Lightning equivalent for the "Create new Account" URL is lightning/o/Account/new and for a specific record is lightning/r/Account/<Id>/view. When you build Lightning components, you can use the navigation service to get these URLs dynamically.
You have inline test methods, which haven't been allowed since an API version well before I started on the platform. Break those out into a separate test class.

Identity Server 4. Token Endpoint, Password Grant. How do I check acr_values?

I suspect this is very simple but I can't find exactly what I need to do.
I am trying to get a password Grant enabled, token endpoint, working with name/password/SomethingExtra
It all works with just name and password. I can see my "Data:SomethingExtra" in acr_values on the server but only in the GetProfileDataAsync override.
So, I can pick up the acr_values in the token generation (GetProfileDataAsync) but I want to "validate" the user with this extra data. How do I test my acr_values at validation?
I suspect there is a method I can override to pick up the "login request" with the extra acr_values so I can decide to return a token or Access Denied much the same was I do with an interactive login using Quickstart web pages.
But what do I override to allow me to authenticate against 3 values?
If you are using password grant then you will have implemented IResourceOwnerPasswordValidator to validate your passwords. You can get the acr values in this class as follows:
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) {
string acrValues = context.Request.Raw.Get("acr_values");
IEnumerable<string> values = acrValues.Trim().Split(new[] { ' ' });
string extraDataAcr = values.FirstOrDefault(x => x.StartsWith("ExtraData:"));
string extraDataValue extraDataAcr?.Substring("ExtraData:".Length);
After a bit of digging...might save someone some time
public class ACustomTokenRequestValidator : ICustomTokenRequestValidator
{
private readonly UserManager<ApplicationUser> _userManager;
public ACustomTokenRequestValidator(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task ValidateAsync(CustomTokenRequestValidationContext context)
{
if (context?.Result?.ValidatedRequest?.GrantType != null &&
context.Result.ValidatedRequest.GrantType.ToUpper() == "PASSWORD") // Only interested in password Grant
{
var acr_values = new Dictionary<string, string>();
string username = string.Empty;
string error = string.Empty;
string Tester = string.Empty;
bool ok = true;
if (context.Result.ValidatedRequest.Raw != null)
{
var reqParamsDict = context.Result.ValidatedRequest.Raw.ToDictionary();
if (reqParamsDict.ContainsKey("acr_values"))
{
var raw = reqParamsDict["acr_values"].Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
acr_values = raw.Select(item => item.Split(':', 2, StringSplitOptions.RemoveEmptyEntries)).ToDictionary(s => s[0], s => s[1]);
}
if (reqParamsDict.ContainsKey("username")) // Should always be there, name/password check would have failed already
{
username = reqParamsDict["username"];
}
else
{
ok = false;
error = "username missing from request";
}
if (ok && acr_values.ContainsKey("ExtraField")) // Could be missing
{
Tester = acr_values["ExtraField"];
}
else
{
ok = false;
error = "ExtraField missing from request";
}
if (ok)
{
if (context.Result.ValidatedRequest.Scopes.Contains("API_Name"))
{
var user = await _userManager.FindByNameAsync(username);
if (user != null)
{
if ( user.ExtraField != Tester )
{
ok = false;
error = "Failed extra test";
}
}
else
{
ok = false;
error = "User not found";
}
}
}
}
if (!ok)
{
context.Result.IsError = true;
context.Result.Error = error;
}
}
}
}
For completeness this is my Postman setup to get it working
[https://i.stack.imgur.com/BtihJ.png][1]

Use WebBrowser control in page instead of popup for Identity Server 4 login

I am using Identity Server 4 for authentication on my WPF MVVM app. Currently, when the user wants to log in, a popup window appears with the login screen and the info gets passed back through the OidcClientOptions. However, instead of a popup window, I want the login page to show up on a WebBrowser control in the actual application. How can I accomplish this?
My Login code:
public class Login
{
private OidcClient _oidcClient = null;
LoginResult result = null;
AccessToken accessToken = new AccessToken();
public async void LoginPage()
{
var options = new OidcClientOptions()
{
Authority = "https://localhost:5001/",
ClientId = "wpf",
ClientSecret = "secret",
Scope = "openid WebAPI",
RedirectUri = "http://localhost/signin-oidc",
Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
Browser = new WpfEmbeddedBrowser();
};
_oidcClient = new OidcClient(options);
try
{
result = await _oidcClient.LoginAsync();
}
catch (Exception ex)
{
return;
}
if (result.IsError)
{
}
else
{
accessToken.WriteToken(result.AccessToken);
App.Current.Properties["AccessToken"] = result.AccessToken;
}
}
}
Current WpfEmbeddedBrowser I'm using:
public class WpfEmbeddedBrowser : IBrowser
{
private BrowserOptions _options = null;
public WpfEmbeddedBrowser()
{
}
public async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
{
_options = options;
var window = new Window()
{
Width = 900,
Height = 625,
Title = "IdentityServer Login"
};
// Note: Unfortunately, WebBrowser is very limited and does not give sufficient information for
// robust error handling. The alternative is to use a system browser or third party embedded
// library (which tend to balloon the size of your application and are complicated).
var webBrowser = new WebBrowser();
var signal = new SemaphoreSlim(0, 1);
var result = new BrowserResult()
{
ResultType = BrowserResultType.UserCancel
};
webBrowser.Navigating += (s, e) =>
{
if (BrowserIsNavigatingToRedirectUri(e.Uri))
{
e.Cancel = true;
result = new BrowserResult()
{
ResultType = BrowserResultType.Success,
Response = e.Uri.AbsoluteUri
};
signal.Release();
window.Close();
}
};
window.Closing += (s, e) =>
{
signal.Release();
};
window.Content = webBrowser;
window.Show();
webBrowser.Source = new Uri(_options.StartUrl);
await signal.WaitAsync();
return result;
}
private bool BrowserIsNavigatingToRedirectUri(Uri uri)
{
return uri.AbsoluteUri.StartsWith(_options.EndUrl);
}
}

Can't get Novell.Directory.Ldap.NETStandard library to query

I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.
I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.
Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.
So I am trying to use the Novell.Directory.Ldap.NetStandard library.
Here is the code the other developer sent me:
public static List<UserProfileModel> GetADUsers(string alias)
{
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
// Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
de2.Path = ConfigurationManager.AppSettings["AD_Path"];
de2.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de2;
deSearch.Filter = "(samaccountname=*" + alias + "*)";
LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));
SearchResultCollection results = deSearch.FindAll();
String raw = "";
LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));
if (results.Count > 0)
{
foreach (SearchResult item in results)
{
UserProfileModel userProfileModel = new UserProfileModel();
userProfileModel.Name = GetADProperty("name", item);
userProfileModel.email = GetADProperty("mail", item);
userProfileModel.identity = GetADProperty("userPrincipalName", item);
userProfileModel.first_name = GetADProperty("givenName", item);
userProfileModel.last_name = GetADProperty("sn", item);
users.Add(userProfileModel);
raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
}
LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
}
}
catch (Exception e)
{
LOGGER.Error("Unable to Query Active Directory", e);
}
return users;
}
I need to translate this into Novell's LDAP library.
Here is my attempt:
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = "ourOrg.gov";
string loginDn = #"ourOrg\myName";
string password = "myPass";
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchResults results = con.Search(
"cn=users,dc=ourOrg,dc=gov",
LdapConnection.SCOPE_ONE,
"samaccountname=*",
null,
false);
// NO RESULTS:(
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
I don't get an error.
But there are 0 results.
I originally had this part:
"samaccountname=*",
like:
"samaccountname={alias}",
but I'm just trying to get back results at this point.
I got this working:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hrsa.Core.Web.App.Controllers.Api
{
[Route("api/[controller]")]
public class ActiveDirectoryController : Controller
{
private readonly AppSettings _appSettings;
public ActiveDirectoryController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = _appSettings.HrsaLdapHost; // ourOrgName.gov
string loginDn = _appSettings.AdUser;
string password = _appSettings.AdPassword;
string searchBase = _appSettings.HrsaAdSearchBase;
string searchFilter = $"(samaccountname=*{alias}*)";
string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
"description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchQueue queue = con.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
attributes,
false,
(LdapSearchQueue)null,
(LdapSearchConstraints)null);
LdapMessage message;
while ((message = queue.getResponse()) != null)
{
if (message is LdapSearchResult)
{
LdapEntry entry = ((LdapSearchResult)message).Entry;
LdapAttributeSet attributeSet = entry.getAttributeSet();
users.Add(new UserProfileModel
{
Cn = attributeSet.getAttribute("cn")?.StringValue,
UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
St = attributeSet.getAttribute("st")?.StringValue,
Givenname = attributeSet.getAttribute("givenname")?.StringValue,
Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
Description = attributeSet.getAttribute("description")?.StringValue,
Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
Department = attributeSet.getAttribute("department")?.StringValue,
Displayname = attributeSet.getAttribute("displayname")?.StringValue,
Name = attributeSet.getAttribute("name")?.StringValue,
Mail = attributeSet.getAttribute("mail")?.StringValue,
GivenName = attributeSet.getAttribute("givenName")?.StringValue,
Sn = attributeSet.getAttribute("sn")?.StringValue
});
}
}
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

Resources