Is it possible to set a boolean-value claims in your Identity Token with Duende Identity Server 5? - identityserver4

I'm trying to set a custom claim with some code for Duende Identity Server 5.2.3.
The claim works / is added, but it's a string and not a boolean.
I've notied -another- claim inthe JWT that is a boolean so I'm wondering, can I do this also?
Here's the code and then the sample JWT:
public class CustomTokenService : DefaultTokenService
{
public override async Task<Token> CreateIdentityTokenAsync(TokenCreationRequest request)
{
var token = await base.CreateIdentityTokenAsync(request);
bool isThisInAGracePeriod = true; // for example ...
// This doesn't work. There's no bool overload, for the 2nd argument.
// var myClaim = new Claims("in_grace_period", isThisInAGracePeriod);
// I need to convert the bool to a string, using ToString();
var myClaim = new Claims("in_grace_period", isThisInAGracePeriod.ToString());
token.Claims.Add(myClaim);
}
}
so notice:
email_verified is a bool value
in_grace_period is a string value (because I had to ToString() it :( )
Is it possible to add my custom claim as a bool so it ends up looking like how email_verified is serialized out to the token payload?

Yes, Claim class has a constructor that accepts 3 parameters and the 3rd one is value type.
var claim = new Claim(
type: "in_grace_period",
value: isThisInAGracePeriod.ToString().ToLower(),
valueType: ClaimValueTypes.Boolean);

Related

It is necessary to perform the planned action through the apex scheduler

i have this code:
public static String currencyConverter() {
allCurrency test = new allCurrency();
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http();
request.setEndpoint(endPoint);
request.setMethod('GET');
response = http.send(request);
String JSONresponse = response.getBody();
currencyJSON currencyJSON = (currencyJSON)JSON.deserialize(JSONresponse, currencyJSON.class);
test.USD = currencyJSON.rates.USD;
test.CAD = currencyJSON.rates.CAD;
test.EUR = currencyJSON.rates.EUR;
test.GBP = currencyJSON.rates.GBP;
Log__c logObject = new Log__c();
logObject.Status_Code__c = String.valueOf(response.getStatusCode());
logObject.Response_Body__c = response.getBody();
insert logObject;
if (response.getStatusCode() == 200) {
Exchange_Rate__c ExchangeRateObject = new Exchange_Rate__c();
ExchangeRateObject.CAD__c = currencyJSON.rates.CAD;
ExchangeRateObject.EUR__c = currencyJSON.rates.EUR;
ExchangeRateObject.GBP__c = currencyJSON.rates.GBP;
ExchangeRateObject.USD__c = currencyJSON.rates.USD;
ExchangeRateObject.Log__c = logObject.id;
insert ExchangeRateObject;
}
return JSON.serialize(test);
}
Here I am getting different currencies and then calling them in LWC and also I create two objects with values.
I want these objects to be created every day at 12PM.
Tell me how to implement this through the apex scheduler.
You need a class that implements Schedulable. Can be this class, just add that to the header and add execute method. Or can be separate class, doesn't matter much.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Something like
public with sharing MyClass implements Schedulable{
public static String currencyConverter() { ... your method here }
public void execute(SchedulableContext sc) {
currencyConverter();
}
}
Once your class saves OK you should be able to schedule it from UI (Setup -> Apex Classes -> button) or with System.schedule 1-liner from Developer Console for example.
Alternative would be to have a scheduled Flow - but that's bit more work with making your Apex callable from Flow.
P.S. Don't name your variables test. Eventually some time later you may need "real" stuff like Test.isRunningTest() and that will be "fun". It's like writing
Integer Account = 5; // happy debugging suckers

Getting socket error while accessing azure cognitive search index

I have created an index in the azure portal and I am trying to access the index in my code to get the data. Everytime I do it I get a {System.Net.Sockets.SocketException (11001): No such host is known at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)}.
Is there anything I can do for this?
Below is my code
static void Main(string[] args)
{
Index();
}
public static DocumentSearchResult<SearchResult> Index()
{
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
string serviceName = configuration["SearchServiceName"];
string key = configuration["SearchServiceQueryApiKey"];
//Creating search client
SearchServiceClient serviceClient = new SearchServiceClient(serviceName, new SearchCredentials(key));
SearchIndexClient indexClient = new SearchIndexClient(serviceName, "cognitivesearchpoc", new SearchCredentials(key));
SearchParameters parameters;
DocumentSearchResult<SearchResult> results;
parameters = new SearchParameters() { Select = new[] { "*" } };
return indexClient.Documents.Search<SearchResult>("*");
}
The error message is telling you that the host name to which you’re trying to connect is incorrect. Use just the host name portion of your service endpoint as the service name. In your case, that’s just “devglobalsearch” without the DNS suffix.

Save Cookie in Silverlight Application

I have a silverlight Web Application and want to save user credentials if it checks "Keep me signed in" checkbox.
if (KeepMeSignedIn)
{
SetCookie("CECrd", userName, password);
}
The Set cookie function is as folows..
private static void SetCookie(string key, string uname, string password)
{
string cookieName = "CECrd";
string oldCookie = HtmlPage.Document.GetProperty(cookieName) as String;
DateTime expiration = DateTime.UtcNow + TimeSpan.FromDays(2000);
string cookie = String.Format("{0}={1}={2};expires={3}",key,uname, password, expiration.ToString("R"));
HtmlPage.Document.SetProperty(cookieName, cookie);
}
But i am unable to save the cookie in the browser.
Please help me out.
Cookies consist of name-value "pairs"
e.g.
Name=value
AnotherName=AnotherValue
expires=somedate
Your string.format has a property with 2 equals signs in it!
string cookie = String.Format("{0}={1}={2};expires={3}",key,uname, password, expiration.ToString("R"))
Which generates "{key}={uname}={password};expires={somedate2000daysfromnow}" which is two entries:
{key}={uname}={password}; // invalid
expires={somedate2000daysfromnow} // Valid

[RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with #play.db.jpa.Transactional]

this is the problem once i try to save data into db with sql statement insert.
my function is this:
public void save(){
JPA.em().persist(this);
}
and
public static Result registered() {
Form<User> requestform = form(User.class).bindFromRequest();
if(requestform.hasErrors()){
return badRequest("<p>fehlerhafte eingabe!</p>").as("text/html");
} else {
User user = requestform.get();
String fullname = user.fullname;
String email = user.email;
String password = user.password;
String username = user.username;
new User(username, password, fullname, email).save();
}
return redirect(controllers.routes.Application.index());
}
thanks for help
It is just like the debugging message says, you do not have an entity manager bound to your methods because they are not marked as transactions.
#play.db.jpa.Transactional
public static Result registered() {
Also, if you are using EBean, you could just extend Model for your User class, which comes with many handy built in functions for database use, see documentation here: http://www.playframework.org/documentation/2.0.1/JavaEbean

How do you set a cookie for a web request in Silverlight

I want to set a cookie value for a http POST request, caqn this be done in Silverlight?
If so which class should I use HttpWebRequest, WebCLient or something else?
I think you can define the headers with the HttpWebRequest, so it's easy just define the Cookie header with the correct value, you can find a little help here.
To set the cookie:
HtmlPage.Document.SetProperty("cookie", value);
where value is something like "mykey=abcdef;".
To read it (key in this case is "mykey":
string[] cookies = HtmlPage.Document.Cookies.Split(';');
foreach (string cookie in cookies)
{
string[] keyValuePair = cookie.Split('=');
if (keyValuePair.Length == 2 && key == keyValuePair[0].Trim())
return keyValuePair[1].Trim();
}
To delete it:
string oldCookie = HtmlPage.Document.GetProperty("cookie") as String;
DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
HtmlPage.Document.SetProperty("cookie", cookie);

Resources