Multiple headers required in Swashbuckle for OpenAPI authentication - swashbuckle

I have an API that requires two headers, a "user ID" and a "secret". I am failing to find a way to get them listed in the OpenAPI output as both needed, they are shown as separate options for authorization. OpenAPI says it can do this for Multiple API Keys (leave out a dash) but I cannot find a way to specify that the two are related in code. Is this possible in Swashbuckle? (Am using .Net Core 3.1)
options.AddSecurityDefinition("appkey", new OpenApiSecurityScheme
{
Description = "Unique application key (user ID)",
In = ParameterLocation.Header,
Name = CustomAuthenticationOptions.ApplicationKeyHeaderName,
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityDefinition("secret", new OpenApiSecurityScheme
{
Description = "Secret key (password)",
In = ParameterLocation.Header,
Name = CustomAuthenticationOptions.SecretKeyHeaderName,
Type = SecuritySchemeType.ApiKey,
});

Related

Flutter AWS Auth: How to get custom user attribute?

How do I get in Flutter, the cognito custom user attribute for user?
await Amplify.Auth.fetchUserAttributes();
returns only user attributes but not the custom defined ones.
(I have added the attribute to the schema and I am sure it's there, in the AWS UI it's there.)
The fetchUserAttributes function returns a list of AuthUserAttributes including the custom ones you've defined. When you have that list you can iterate through it, and get the attributes you want.
const res = await Amplify.Auth.fetchUserAttributes();
for (var attr in res) {
if (attr.userAttributeKey == CognitoUserAttributeKey.custom('customAttr') {
customAttr = attr.value;
}
}
If the custom attribute isn't there, make sure the user have that attribute.
The issue was that these custom attributes, after they are created, they are not by default readable or writable.
For further explanations, check https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-attribute-permissions-and-scopes
Go to cognito - app clients - details - and very bottom to change permissions

Unable to refresh dynamic data source in PowerBI service via using anonymous web API access?

This relates to my earlier question - How to iterate/loop through next pages in an API request in PowerQuery/PowerBI? ; which was resolved using below code:
//Declare base variables
let
BaseURL = "https://api.aaaaaa.com",
Entity = "/api/v1/user?&limit=1000",
Token = "zzzzzzzzzzzzzzzzzzzzzzzzzzzz",
Options = [Headers=[APITOKEN=Token]],
URL = BaseURL & Entity,
//Define a function that would take step/page as parameter and return results
GetData=(page as number) =>
let
Source = Json.Document(Web.Contents(URL & "&step=" & Number.ToText(page), Options)),
Data = try Source[results] otherwise null
in
Data,
//Iterate over GetData () to return all the records until last page i.e. until no "result" is retrieved from the API call
GeneratePageList =
List.Generate( ()=>
[Result = try GetData(1) otherwise null, Page=1],
each [Result] <> null,
each [Result = try GetData([Page]+1) otherwise null, Page=[Page]+1],
each [Result]
)
in
GeneratePageList
However, once this code is published to PowerBI service, we cannot schedule refresh for it, since it gives below error as:-
This dataset includes a dynamic data source. Since dynamic data sources aren't refreshed in the Power BI service, this dataset won't be refreshed. Learn more: https://aka.ms/dynamic-data-sources.
• Data source for Query1Discover Data Sources
Tried RelativePath & Query method as suggested here - https://blog.crossjoin.co.uk/2016/08/16/using-the-relativepath-and-query-options-with-web-contents-in-power-query-and-power-bi-m-code/ and here-
https://blog.crossjoin.co.uk/2019/04/25/skip-test-connection-power-bi-refresh-failures/
But, without any luck, see below how am using it:
let
BaseURL = "https://api.crewhu.com",
Entity = "/api/v1/user?&limit=1000&step=",
Token = "60afbdaf5d7d584762771f36",
Options = [Headers=[X_CREWHU_APITOKEN=Token]],
URL = BaseURL & Entity,
//Define a function that would take step/page as parameter and return results
GetData=(page as number) =>
let
Source = Json.Document(Web.Contents(BaseURL & [RelativePath = Entity, Query=[page]], Options)),
The BaseURL is reachable; but redirects to the login page, where our admin credentials (username+password) on the vendor site works well. However, same credentials do not work when using "Basic" connection method during accessing Web Content. Therefore, tried adding #Authorization = Basic in the header along with API key like - [Headers=[Authorization = Basic, X_CREWHU_APITOKEN=Token]]; but this also didn't work.
We've only got an Open API token/key from the vendor; but even that token/key also doesn't work from when providing that in "Web API" section during connecting/accessing Web Content, it gives error as:- "a web api key can only be specified when a web api key name is provided", but the same key/token works well from within PowerQuery (M) code using anonymous web api call method.
Have tried multiple permutation combinations of providing key/token in the username/password fields as suggested in some sites, but still no luck.

Django Rest Framework include_docs_urls adding _0 to action

We have urls in our Django (Rest Framework) applications like:
r'^endpoint/(?P<item>[a-z_-]+)/$'
r'^endpoint/(?P<item>[a-z_-]+)/(?P<version>[0-9]+(\.[0-9])?)/$'
Both have POST methods available.
We've been using Swagger for a while to document our API but wanted to look at the coreapi documentation included in Django Rest Framework.
Going through our documentation based on the above structure the coreapi action results in:
# Initialize a client & load the schema document
client = coreapi.Client()
schema = client.get("http://localhost:8081/docs/")
# Interact with the first url
action = ["app", "endpoint > create"]
# Interact with the second url
action = ["app", "endpoint > create_0"]
I can understand where create_0 is coming from, but ideally it would add the keyword name as a suffix instead, e.g. create_version.
Is this possible?
Having two keywords right after each other seems to be the problem.
r'^endpoint/(?P<item>[a-z_-]+)/$'
r'^endpoint/(?P<item>[a-z_-]+)/(?P<version>[0-9]+(\.[0-9])?)/$'
Should be replaced with:
r'^endpoint/(?P<item>[a-z_-]+)/$'
r'^endpoint/(?P<item>[a-z_-]+)/version/(?P<version>[0-9]+(\.[0-9])?)/$'
That will give you:
action = ["endpoint", "item > version > create"]
Which looks much cleaner.

Unable to authenticate in accessing Dynamic CRM Online Web Service

I need to utilize Dynamic CRM Data Service Endpoint exposed to get data from one of the methods.
Service(microsoft) account has access to this service.
I've tried authenticating to Discovery Service and Organization Service using sample code provided here [https://msdn.microsoft.com/en-us/library/hh675404.aspx] and succeed. However am not able to use same authentication to access data Service as I could find anyway to relate Data Service with the other two. Doing basic authentication using Network Credentials does not work.
I have downloaded the CSDL exposed and added that as service reference to my project, which created an class of web service which extends from DataServiceContext. Am trying to retrieve data of one of the methods using LinQ queries. It returs following error:
"The response payload is a not a valid response payload. Please make sure that the top level element is a valid Atom or JSON element or belongs to 'http://schemas.microsoft.com/ado/2007/08/dataservices' namespace." On capturing using fiddle I realized that on hitting data service URL it is redirected to sign in page 'login.microsoftonline.com/'
Can anybody suggest a way to authenticate the user to access Data Serivce?
Adding code:
//<snippetAuthenticateWithNoHelp1>
IServiceManagement<IDiscoveryService> serviceManagement =
ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
new Uri(_discoveryServiceAddress));
AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;
// Set the credentials.
AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);
String organizationUri = String.Empty;
// Get the discovery service proxy.
using (DiscoveryServiceProxy discoveryProxy =
GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
{
// Obtain organization information from the Discovery service.
if (discoveryProxy != null)
{
// Obtain information about the organizations that the system user belongs to.
OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
// Obtains the Web address (Uri) of the target organization.
organizationUri = FindOrganization(_organizationUniqueName,
orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
}
}
//</snippetAuthenticateWithNoHelp1>
if (!String.IsNullOrWhiteSpace(organizationUri))
{
//<snippetAuthenticateWithNoHelp3>
IServiceManagement<IOrganizationService> orgServiceManagement =
ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
new Uri(organizationUri));
// Set the credentials.
AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);
// Get the organization service proxy.
using (OrganizationServiceProxy organizationProxy =
GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
{
// This statement is required to enable early-bound type support.
organizationProxy.EnableProxyTypes();
// Now make an SDK call with the organization service proxy.
// Display information about the logged on user.
Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
new WhoAmIRequest())).UserId;
SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity<SystemUser>();
Console.WriteLine("Logged on user is {0} {1}.",
systemUser.FirstName, systemUser.LastName);
Uri x = new Uri("https://<MyOrgainzationName>.crm.dynamics.com/XRMServices/2011/OrganizationData.svc/");
MyOrgainzationContext saContext = new MyOrgainzationContext(x);
NetworkCredential nc = new NetworkCredential();
nc.UserName = "*****#microsoft.com";
nc.Password = "********";
saContext.Credentials = nc;
var query_where3 = from c in saContext.new_productSet
select new
{
ProductStatus = c.new_ProductStatus,
LineofBusiness = c.new_LineofBusiness
};
var temp = saContext.Entities;
foreach (var c in query_where3)
{
System.Console.WriteLine("ProductStatus: " +
c.ProductStatus +
"\t\t\t" +
"LineofBusiness: " +
c.LineofBusiness);
}
}
//</snippetAuthenticateWithNoHelp3>
}
MyOrganizationContext is the context class created on adding CSDL file exposed at service endpoints
Have a look at the CRM Web Api Preview: https://msdn.microsoft.com/en-us/dynamics/crm/webapipreview.aspx. You can call this endpoint from outside xRM and you can authenticate with OAuth 2.0.

Call Profile Provider By Name in Profile config

I have a legacy system (sitecore 6.1) which is already have one profile provider in plave as default profile for admin section.
Now, i need to impelement another customised SQL profile provider (in a different table) for normal user.
But my question is How dose system know which profile provider to use in code?
Is there any thing I can do similar as :
System.Web.Security.Membership.Providers[providerString];
So that I can call customised profile provider in my code accordingly.
Or what would be the best practice in this case.
I've wasted like 1 hour try to go through sitecore docs, but not much available there.
Here's some code that I recently did to set up some custom profile stuff for a client using the Email Campaign Manager. Granted this code uses some classes specific to ECM, it creates a new user, initializes a profile class and then assigns that profile to the new user. Then it sets some custom properties for the user that was just created. It shows you how to call the profile based on the user as well as assigning a profile to use for that user. This might help or maybe help someone else.
public static void Process(List<Subscriber> userItems, Item targetAudienceDefinitionItem)
{
foreach (Subscriber user in userItems)
{
// you can also just pass it the id of the target audience as a string
Sitecore.Modules.EmailCampaign.TargetAudienceBase target = Sitecore.Modules.EmailCampaign.TargetAudience.FromItem(targetAudienceDefinitionItem);
string campaignname = target.ManagerRoot.Settings.CommonDomain;
string realUsername = campaignname + "\\" + user.UserName;
using (new SecurityDisabler())
{
User newUser;
if (!Sitecore.Security.Accounts.User.Exists(realUsername))
{
// create a new user and assign it to the email domain specified in the manager root item
newUser = Sitecore.Security.Accounts.User.Create(campaignname + "\\" + user.UserName, System.Web.Security.Membership.GeneratePassword(8,1));
}
else
// get back the existing user
newUser = User.FromName(realUsername, false);
// get back the current user profile
UserProfile subscriber = newUser.Profile;
// reset the profile to be the profile specified in the manager root
subscriber.ProfileItemId = target.ManagerRoot.Settings.SubscriberProfile;
subscriber.Save();
// built in properties are set like this
subscriber.Email = user.Email;
// set custom property value
subscriber["Address"] = user.Address;
// or long method
subscriber.SetCustomProperty("Address", user.Address);
subscriber.Save();
// now subscribe the user to the target audience subscriber list
target.Subscribe(Contact.FromName(newUser.Name));
}
}
}