approve an order through paypal Using Saved Card Vault v2 api - api

The reason why we would want to use the vault is so that we don’t have to store sensitive credit card information on our own servers. We simply reference the payment method via a provided vault ID, meaning that we don’t have to deal with many PCI compliance regulations with storing the credit cards ourselves.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-m.sandbox.paypal.com/v2/checkout/orders',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"intent": "CAPTURE",
"purchase_units": [
{
"items": [
{
"name": "T-Shirt",
"description": "Green XL",
"quantity": "1",
"unit_amount": {
"currency_code": "USD",
"value": "100.00"
}
}
],
"amount": {
"currency_code": "USD",
"value": "100.00",
"breakdown": {
"item_total": {
"currency_code": "USD",
"value": "100.00"
}
}
}
}
],
"application_context": {
"return_url": "https://example.com/return",
"cancel_url": "https://example.com/cancel"
}
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Prefer: return=representation',
'PayPal-Request-Id: 232b4c61-b6f7-4c1b-b39c-43e82a1c6daa',
'Authorization: Bearer '
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
A successful request returns the HTTP 201 Created status code and a JSON response body that includes by default a minimal response with the ID, status, and HATEOAS links. If you require the complete order resource representation, you must pass the Prefer: return=representation request header. This header value is not the default.
Example:
{
"id": "1SX99239FX399905E",
"intent": "CAPTURE",
"status": "CREATED",
"purchase_units": [
{
"reference_id": "default",
"amount": {
"currency_code": "USD",
"value": "100.00",
"breakdown": {
"item_total": {
"currency_code": "USD",
"value": "100.00"
}
}
},
"payee": {
"email_address": "john_merchant#example.com",
"merchant_id": "C7CYMKZDG8D6E"
},
"items": [
{
"name": "T-Shirt",
"unit_amount": {
"currency_code": "USD",
"value": "100.00"
},
"quantity": "1",
"description": "Green XL"
}
]
}
],
"create_time": "2022-07-20T00:20:41Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1SX99239FX399905E",
"rel": "self",
"method": "GET"
},
{
"href": "https://www.sandbox.paypal.com/checkoutnow?token=1SX99239FX399905E",
"rel": "approve",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1SX99239FX399905E",
"rel": "update",
"method": "PATCH"
},
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1SX99239FX399905E/capture",
"rel": "capture",
"method": "POST"
}
]
}
What I need is to be able to integrate from the paypal vault the cards returned in v1 with the credit card id CARD-1YE76616JL1119629MCSXFCY
In the documentation I don't see a way to make a payment through the vault in version v1 it could be done but in this one I still don't know how
The sample code was as it was previously done before v2
public function CreatePaymentUsingSavedCardVault($requestData, $credit_card_id) {
try {
///$card = new CreditCard();
//$card->setId($credit_card_id);
// ### Credit card token
// Saved credit card id from CreateCreditCard.
$creditCardToken = new CreditCardToken();
$creditCardToken->setCreditCardId($credit_card_id);
// ### FundingInstrument
// A resource representing a Payer's funding instrument.
// For stored credit card payments, set the CreditCardToken
// field on this object.
$fi = new FundingInstrument();
$fi->setCreditCardToken($creditCardToken);
// ### Payer
// A resource representing a Payer that funds a payment
// For stored credit card payments, set payment method
// to 'credit_card'.
$payer = new Payer();
$payer->setPaymentMethod("credit_card");
$payer->setFundingInstruments(array($fi));
// ### Itemized information
// (Optional) Lets you specify item wise information
$itemListArray = array();
if(isset($requestData['orderItems'])){
foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
$item = new Item();
$array = array_filter($value);
if (count($array) > 0) {
$this->setArrayToMethods($array, $item);
array_push($itemListArray, $item);
}
}
}
$itemList = new ItemList();
if(!empty($itemListArray)){
$itemList->setItems($itemListArray);
}
// ### Additional payment details
// Use this optional field to set additional payment information such as tax, shipping charges etc.
if (isset($requestData['paymentDetails'])) {
$details = new Details();
$this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
}
// ### Amount
// Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
$amount = new Amount();
if (isset($requestData['amount'])) {
$this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
}
$detailsArray = $this->checkEmptyObject((array)$details);
if (!empty($detailsArray)) {
$amount->setDetails($details);
}
// ### Transaction
// A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
$transaction = new Transaction();
$amountArray = $this->checkEmptyObject((array)$amount);
if(!empty($amountArray)){
$transaction->setAmount($amount);
}
$itemListArray = $this->checkEmptyObject((array)$itemList);
if (!empty($itemListArray)) {
$transaction->setItemList($itemList);
}
if (isset($requestData['transaction'])){
$this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
}
// ### Payment
// A Payment Resource; create one using the above types and intent set to sale 'sale'
$payment = new Payment();
$payment->setIntent($requestData['intent']);
$payerArray = $this->checkEmptyObject((array)$payer);
if(!empty($payerArray)){
$payment->setPayer($payer);
}
$transactionArray = $this->checkEmptyObject((array)$transaction);
if(!empty($transactionArray)){
$payment->setTransactions(array($transaction));
}
$requestArray = clone $payment;
$payment->create($this->_api_context);
$returnArray['RESULT'] = 'Success';
$returnArray['PAYMENT'] = $payment->toArray();
$returnArray['RAWREQUEST']=$requestArray->toJSON();
$returnArray['RAWRESPONSE']=$payment->toJSON();
$paypal = new PayPal(array());
$paypal->TPV_Parse_Request($payment->toArray(), array(), 24, true, false, 'PayPal_Rest');
return $returnArray;
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
return $this->createErrorResponse($ex);
}
}

Related

PowerBI Create Dataset from a Postgresql datasource using REST API

I created a datasource behind gateway for using rest API. Datasource got created. However, now I want to add a table(create a dataset) from the created datasource to use it in a report. However, I am getting the below error from API.
{
"error": {
"code": "FailedToDeserializeDatasetError",
"pbi.error": {
"code": "FailedToDeserializeDatasetError",
"parameters": {},
"details": [],
"exceptionCulprit": 1
}
}
}
API request body:
{
"datasources": [
{
"gatewayId":"gateway_id",
"datasourceId": "datasource_id",
"datasourceType": "PostgreSql",
"connectionDetails": "{\"server\":\"server_address\",\"database\":\"database_name\"}",
"credentialType": "Basic",
"credentialDetails": {
"privacyLevel": "None",
"useEndUserOAuth2Credentials": false
}
}
],
"defaultMode": "Push",
"name": "API DS 1",
"tables": [
{
"name":"currency_rates",
"description": "DS Table 1 Demo API",
"columns":[
{
"name":"id",
"dataType":"Int64"
},
{
"name":"traded_on",
"dataType":"DateTime"
},
{
"name":"currency_code",
"dataType": "string"
},
{
"name":"close",
"dataType": "Double"
}
]
}
]
}
Not sure what is wrong here.
API Reference: https://learn.microsoft.com/en-us/rest/api/power-bi/push-datasets/datasets-post-dataset-in-group

IdentityServer4 {"error":"invalid_client"}

I am using IdentityServer4 (version 3.0.2.0) and facing no client id issue. The exact error is
ERROR| No client with id 'myclientId' found. aborting
Startup.cs of IdentityServer4 project
services.AddIdentityServer()
.AddDeveloperSigningCredential()
// .AddInMemoryCaching()
.AddInMemoryApiResources(Configuration.GetSection("IdentityServer:ApiResources"))
.AddInMemoryClients(Configuration.GetSection("IdentityServer:Clients"))
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = Convert.ToBoolean(Configuration["CleanUp:IsEnabled"]);
options.TokenCleanupInterval = Convert.ToInt32(Configuration["CleanUp:Interval"]); // interval in seconds
});
Also, I have sha256 converted client_secret in appsettings.json file, sample appsettings.json
"IdentityServer": {
"ApiResources": [
{
"Name": "myapi",
"DisplayName": "my api",
"Scopes": [
{
"Name": "mycustomscope"
},
{
"Name": "openid"
}
],
"ApiSecrets": [
{
"Value": "my sha256 converted secret string",
"Description": "my api"
}
]
}
],
"Clients": [
{
"Enabled": true,
"ClientId": "myclientId",
"AccessTokenLifetime": 100000000,
"ProtocolType": "oidc",
"RequireClientSecret": true,
"IdentityTokenLifetime": 300,
"AuthorizationCodeLifetime": 300,
"ConsentLifetime": 300,
"AbsoluteRefreshTokenLifetime": 2592000,
"SlidingRefreshTokenLifetime": 1296000,
"RefreshTokenExpiration": true,
"AlwaysSendClientClaims": false,
"ClientName": "myclientId",
"ClientSecrets": [
{
"Value": "my sha256 converted secret string",
"Type": "SharedSecret"
}
],
"AllowedGrantTypes": [ "client_credentials", "password" ],
"AllowedScopes": [ "mycustomscope", "openid" ],
"RequireConsent": true
}
]
}
Sample token request from postman/JMeter
url: https://myip:port/myappPool/connect/token
method type: POST
Parameters are:
{
"client_id":"myclientId",
"client_secret": "plaintext secret",
"username":"abcdefghijkl",
"scope":"mycustomscope",
"device_id":"custom property",
"password": "mypassword",
"grant_type":"password",
"app_version":"custom property",
"hashed_value":"custom property"
}
I am posting answer to my own question because I have solved the issue. For me below given field was making an issue. After removing this field, the code ran just fine.
"RefreshTokenExpiration": true
Turns out, IdentityServer4.Models.Client does not have any boolean field named RefreshTokenExpiration but class object.

How to update the state of store when we add new data by api

I am new in React-native and Redux, I am trying to do CRUD operation. How to update the state of store when we add data by api. I am calling Get Business Api in may action. and I store it into Store.
business action:
export const getBusinessByAliases = (aliases) => {
return (dispatch) => {
dispatch(getBusinessByAliasesData(aliases))
//API CALL
getBusiness(aliases)
.then(response=>{
//HERE I GET WHOLE BUSINESS DATA
dispatch(getBusinessByAliasesSuccess(response.data.business))
})
.catch(err => {
console.log("err",err)
dispatch(getBusinessByAliasesFailure(err))
})
}
}
business data is:
business:[
"id": "17bfdde3-bc04-4a9c-87e7-7530ded1b929",
"inserted_at": "2019-07-10T09:47:41",
"name": "Business2",
"employees": [
{
"nickname": "xyz",
"settings": null,
"user": {
"email": null,
"first_name": null,
"id": "582f5d07-146e-4a81-a6c0-7dd5208b43b2",
"image_id": null,
"inserted_at": "2019-07-02T13:41:06",
"last_name": null,
"phone": "+911234567890"
}
}
],
"services": [
{
"id": "34bd8c80-41e1-459a-bc09-d88a6894bd42",
"name": "Gsgsha",
"settings": {
"color": "#039BE5",
"duration": 4,
"price": 6
}
}
],
]
Now i am adding customer by calling create employee api in another action
employee action :
export const createNewEmployee = (businessName,data) => {
//console.log("whole data", data)
return (dispatch) => {
dispatch(createEmployee(businessName,data))
// API CALL
createEmployees(businessName,data)
.then(response=>{
//IN RESPONSE I GET SUCCESS MESSAGE WITH TRANSACTION ID
dispatch(createEmployeeSuccess(response.data.transaction_id))
})
.catch(err => {
console.log("errEmp",err)
dispatch(createEmployeeFailure(err))
})
}
}
Now, How do I update by the business state which contains all data with my new added employee entry?
I think the best solution is that your endpoint should response the new business object with all employes or only the new list of employes.
Keep in mind that your server can be modified by a lot of app clients, if you need to keep the information updated, you need to implement a Firebase protocol to update your store every time.

How to correctly validate array of objects using JustinRainbow/JsonSchema

I have code that correctly validates an article returned from an endpoint that returns single articles. I'm pretty sure it's working correctly as it gives a validation error when I deliberately don't include a required field in the article.
I also have this code that tries to validate an array of articles returned from an endpoint that returns an array of articles. However, I'm pretty sure that isn't working correctly, as it always says the data is valid, even when I deliberately don't include a required field in the articles.
How do I correctly validate an array of data against the schema?
The full test code is below as a standalone runnable test. Both of the tests should fail, however only one of them does.
<?php
declare(strict_types=1);
error_reporting(E_ALL);
require_once __DIR__ . '/vendor/autoload.php';
// Return the definition of the schema, either as an array
// or a PHP object
function getSchema($asArray = false)
{
$schemaJson = <<< 'JSON'
{
"swagger": "2.0",
"info": {
"termsOfService": "http://swagger.io/terms/",
"version": "1.0.0",
"title": "Example api"
},
"paths": {
"/articles": {
"get": {
"tags": [
"article"
],
"summary": "Find all articles",
"description": "Returns a list of articles",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Article"
}
}
}
},
"parameters": [
]
}
},
"/articles/{articleId}": {
"get": {
"tags": [
"article"
],
"summary": "Find article by ID",
"description": "Returns a single article",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"parameters": [
{
"name": "articleId",
"in": "path",
"description": "ID of article to return",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Article"
}
}
}
}
}
},
"definitions": {
"Article": {
"type": "object",
"required": [
"id",
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"title": {
"type": "string",
"description": "The title for the link of the article"
}
}
}
},
"schemes": [
"http"
],
"host": "example.com",
"basePath": "/",
"tags": [],
"securityDefinitions": {
},
"security": [
{
"ApiKeyAuth": []
}
]
}
JSON;
return json_decode($schemaJson, $asArray);
}
// Extract the schema of the 200 response of an api endpoint.
function getSchemaForPath($path)
{
$swaggerData = getSchema(true);
if (isset($swaggerData["paths"][$path]['get']["responses"][200]['schema']) !== true) {
echo "response not defined";
exit(-1);
}
return $swaggerData["paths"][$path]['get']["responses"][200]['schema'];
}
// JsonSchema needs to know about the ID used for the top-level
// schema apparently.
function aliasSchema($prefix, $schemaForPath)
{
$aliasedSchema = [];
foreach ($schemaForPath as $key => $value) {
if ($key === '$ref') {
$aliasedSchema[$key] = $prefix . $value;
}
else if (is_array($value) === true) {
$aliasedSchema[$key] = aliasSchema($prefix, $value);
}
else {
$aliasedSchema[$key] = $value;
}
}
return $aliasedSchema;
}
// Test the data matches the schema.
function testDataMatches($endpointData, $schemaForPath)
{
// Setup the top level schema and get a validator from it.
$schemaStorage = new \JsonSchema\SchemaStorage();
$id = 'file://example';
$swaggerClass = getSchema(false);
$schemaStorage->addSchema($id, $swaggerClass);
$factory = new \JsonSchema\Constraints\Factory($schemaStorage);
$jsonValidator = new \JsonSchema\Validator($factory);
// Alias the schema for the endpoint, so JsonSchema can work with it.
$schemaForPath = aliasSchema($id, $schemaForPath);
// Validate the things
$jsonValidator->check($endpointData, (object)$schemaForPath);
// Process the result
if ($jsonValidator->isValid()) {
echo "The supplied JSON validates against the schema definition: " . \json_encode($schemaForPath) . " \n";
return;
}
$messages = [];
$messages[] = "End points does not validate. Violations:\n";
foreach ($jsonValidator->getErrors() as $error) {
$messages[] = sprintf("[%s] %s\n", $error['property'], $error['message']);
}
$messages[] = "Data: " . \json_encode($endpointData, JSON_PRETTY_PRINT);
echo implode("\n", $messages);
echo "\n";
}
// We have two data sets to test. A list of articles.
$articleListJson = <<< JSON
[
{
"id": 19874
},
{
"id": 19873
}
]
JSON;
$articleListData = json_decode($articleListJson);
// A single article
$articleJson = <<< JSON
{
"id": 19874
}
JSON;
$articleData = json_decode($articleJson);
// This passes, when it shouldn't as none of the articles have a title
testDataMatches($articleListData, getSchemaForPath("/articles"));
// This fails correctly, as it is correct for it to fail to validate, as the article doesn't have a title
testDataMatches($articleData, getSchemaForPath("/articles/{articleId}"));
The minimal composer.json is:
{
"require": {
"justinrainbow/json-schema": "^5.2"
}
}
Edit-2: 22nd May
I have been digging further turns out that the issue is because of your top level conversion to object
$jsonValidator->check($endpointData, (object)$schemaForPath);
You shouldn't have just done that and it would have all worked
$jsonValidator->check($endpointData, $schemaForPath);
So it doesn't seem to be a bug it was just a wrong usage. If you just remove (object) and run the code
$ php test.php
End points does not validate. Violations:
[[0].title] The property title is required
[[1].title] The property title is required
Data: [
{
"id": 19874
},
{
"id": 19873
}
]
End points does not validate. Violations:
[title] The property title is required
Data: {
"id": 19874
}
Edit-1
To fix the original code you would need to update the CollectionConstraints.php
/**
* Validates the items
*
* #param array $value
* #param \stdClass $schema
* #param JsonPointer|null $path
* #param string $i
*/
protected function validateItems(&$value, $schema = null, JsonPointer $path = null, $i = null)
{
if (is_array($schema->items) && array_key_exists('$ref', $schema->items)) {
$schema->items = $this->factory->getSchemaStorage()->resolveRefSchema((object)$schema->items);
var_dump($schema->items);
};
if (is_object($schema->items)) {
This will handle your use case for sure but if you don't prefer changing code from the dependency then use my original answer
Original Answer
The library has a bug/limitation that in src/JsonSchema/Constraints/CollectionConstraint.php they don't resolve a $ref variable as such. If I updated your code like below
// Alias the schema for the endpoint, so JsonSchema can work with it.
$schemaForPath = aliasSchema($id, $schemaForPath);
if (array_key_exists('items', $schemaForPath))
{
$schemaForPath['items'] = $factory->getSchemaStorage()->resolveRefSchema((object)$schemaForPath['items']);
}
// Validate the things
$jsonValidator->check($endpointData, (object)$schemaForPath);
and run it again, I get the exceptions needed
$ php test2.php
End points does not validate. Violations:
[[0].title] The property title is required
[[1].title] The property title is required
Data: [
{
"id": 19874
},
{
"id": 19873
}
]
End points does not validate. Violations:
[title] The property title is required
Data: {
"id": 19874
}
You either need to fix the CollectionConstraint.php or open an issue with developer of the repo. Or else manually replace your $ref in the whole schema, like had shown above. My code will resolve the issue specific to your schema, but fixing any other schema should not be a big issue
EDIT: Important thing here is that provided schema document is instance of Swagger Schema, which employs extended subset of JSON Schema to define some cases of request and response. Swagger 2.0 Schema itself can be validated by its JSON Schema, but it can not act as a JSON Schema for API Response structure directly.
In case entity schema is compatible with standard JSON Schema you can perform validation with general purpose validator, but you have to provide all relevant definitions, it can be easy when you have absolute references, but more complicated for local (relative) references that start with #/. IIRC they must be defined in the local schema.
The problem here is that you are trying to use schema references detached from resolution scope. I've added id to make references absolute, therefore not requiring being in scope.
"$ref": "http://example.com/my-schema#/definitions/Article"
The code below works well.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$swaggerSchemaData = json_decode(<<<'JSON'
{
"id": "http://example.com/my-schema",
"swagger": "2.0",
"info": {
"termsOfService": "http://swagger.io/terms/",
"version": "1.0.0",
"title": "Example api"
},
"paths": {
"/articles": {
"get": {
"tags": [
"article"
],
"summary": "Find all articles",
"description": "Returns a list of articles",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "http://example.com/my-schema#/definitions/Article"
}
}
}
},
"parameters": [
]
}
},
"/articles/{articleId}": {
"get": {
"tags": [
"article"
],
"summary": "Find article by ID",
"description": "Returns a single article",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"parameters": [
{
"name": "articleId",
"in": "path",
"description": "ID of article to return",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "http://example.com/my-schema#/definitions/Article"
}
}
}
}
}
},
"definitions": {
"Article": {
"type": "object",
"required": [
"id",
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"title": {
"type": "string",
"description": "The title for the link of the article"
}
}
}
},
"schemes": [
"http"
],
"host": "example.com",
"basePath": "/",
"tags": [],
"securityDefinitions": {
},
"security": [
{
"ApiKeyAuth": []
}
]
}
JSON
);
$schemaStorage = new \JsonSchema\SchemaStorage();
$schemaStorage->addSchema('http://example.com/my-schema', $swaggerSchemaData);
$factory = new \JsonSchema\Constraints\Factory($schemaStorage);
$validator = new \JsonSchema\Validator($factory);
$schemaData = $swaggerSchemaData->paths->{"/articles"}->get->responses->{"200"}->schema;
$data = json_decode('[{"id":1},{"id":2,"title":"Title2"}]');
$validator->validate($data, $schemaData);
var_dump($validator->isValid()); // bool(false)
$data = json_decode('[{"id":1,"title":"Title1"},{"id":2,"title":"Title2"}]');
$validator->validate($data, $schemaData);
var_dump($validator->isValid()); // bool(true)
I'm not sure I fully understand your code here, but I have an idea based on some assumptions.
Assuming $typeForEndPointis the schema you're using for validation, your item key word needs to be an object rather than an array.
The items key word can be an array or an object. If it's an object, that schema is applicable to every item in the array. If it is an array, each item in that array is applicable to the item in the same position as the array being validated.
This means you're only validating the first item in the array.
If "items" is a schema, validation succeeds if all elements in the
array successfully validate against that schema.
If "items" is an array of schemas, validation succeeds if each element
of the instance validates against the schema at the same position, if
any.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.4.1
jsonValidator don't like mixed of object and array association,
You can use either:
$jsonValidator->check($endpointData, $schemaForPath);
or
$jsonValidator->check($endpointData, json_decode(json_encode($schemaForPath)));

Unable to use IdentityManager API from Postman

I am using postman and I am trying to get the users list from identity Manager. But I am unable to configure the app correctly. I try to get the users from https://localhost/idm/api/users
I get the token with the API+idmgr+openid scopes and I have the Administrator role in my claims.
Here is the startup file:
namespace WebHost
{
internal class Startup
{
public void Configuration(IAppBuilder app)
{
LogProvider.SetCurrentLogProvider(new NLogLogProvider());
string connectionString = ConfigurationManager.AppSettings["MembershipRebootConnection"];
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
Authority = "https://localhost/ids",
ClientId = "postman",
RedirectUri = "https://localhost",
ResponseType = "id_token",
UseTokenLifetime = false,
Scope = "openid idmgr",
SignInAsAuthenticationType = "Jwt",
Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
return Task.FromResult(0);
}
}
});
X509Certificate2 cert = Certificate.Get();
app.Map("/idm", adminApp =>
{
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new string[] { "https://localhost/ids" + "/resources" },
AuthenticationType = "Jwt",
IssuerSecurityTokenProviders = new[] {
new X509CertificateSecurityTokenProvider("https://localhost/ids", cert)
},
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
});
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
var securityConfig = new ExternalBearerTokenConfiguration
{
Audience = "https://localhost/ids" + "/resources",
BearerAuthenticationType = "Jwt",
Issuer = "https://localhost/ids",
SigningCert = cert,
Scope = "openid idmgr",
RequireSsl = true,
};
adminApp.UseIdentityManager(new IdentityManagerOptions()
{
Factory = factory,
SecurityConfiguration = securityConfig
});
});
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = "Login",
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true
};
core.UseIdentityServer(options);
});
}
}
}
What Am I missing?
For those who may want to know how I did it, well I made a lot of search about Owin stuff and how Identity Server works and find out my problem was not that far.
I removed the JwtSecurityTokenHandler.InboundClaimTypeMap
I removed the UseOpenId stuff (don't remove it if you are using an openId external login provider (if you are using google, facebook or twitter, there is classes for that, just install the nuget, it's pretty straight forward)
This section let you configure the bearer token which is the default type token i used in my app(I decided to use password authentication to simplify Postman request to do automatic testing but I still user Code authentication in my apps)
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["AuthorityUrl"],
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { ConfigurationManager.AppSettings["ApiScope"] }
});
I have disabled the IdentityManagerUi interface as I was planning to use the API
app.Map(ConfigurationManager.AppSettings["IdentityManagerSuffix"].ToString(), idmm =>
{
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
idmm.UseIdentityManager(new IdentityManagerOptions()
{
DisableUserInterface = true,
Factory = factory,
SecurityConfiguration = new HostSecurityConfiguration()
{
HostAuthenticationType = Constants.BearerAuthenticationType
}
});
});
And I configure the Identity Server like this:
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = ConfigurationManager.AppSettings["SiteName"],
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true,
};
core.UseIdentityServer(options);
});
In IdentityServerServiceFactory I call this chunk of code:
var clientStore = new InMemoryClientStore(Clients.Get());
And the code for the Client should be something like:
public static Client Get()
{
return new Client
{
ClientName = "PostMan Application",
ClientId = "postman",
ClientSecrets = new List<Secret> {
new Secret("ClientSecret".Sha256())
},
Claims = new List<Claim>
{
new Claim("name", "Identity Manager API"),
new Claim("role", IdentityManager.Constants.AdminRoleName),
},
**Flow = Flows.ResourceOwner**, //Password authentication
PrefixClientClaims = false,
AccessTokenType = AccessTokenType.Jwt,
ClientUri = "https://www.getpostman.com/",
RedirectUris = new List<string>
{
"https://www.getpostman.com/oauth2/callback",
//aproulx - 2015-11-24 -ADDED This line, url has changed on the postman side
"https://app.getpostman.com/oauth2/callback"
},
//IdentityProviderRestrictions = new List<string>(){Constants.PrimaryAuthenticationType},
AllowedScopes = new List<string>()
{
"postman",
"IdentityManager",
ConfigurationManager.AppSettings["ApiScope"],
Constants.StandardScopes.OpenId,
IdentityManager.Constants.IdMgrScope,
}
};
}
On the postman side just do:
POST /ids/connect/token HTTP/1.1
Host: local-login.net
Cache-Control: no-cache
Postman-Token: 33e98423-701f-c615-8b7a-66814968ba1a
Content-Type: application/x-www-form-urlencoded
client_id=postman&client_secret=SecretPassword&grant_type=password&scope=APISTUFF&username=apiViewer&password=ICanUseTheApi
Hope that it will help somebody
Shaer,
I saw your comment and because of that I've created a project (make sure you clone the postmanexample branch) where you can see a working example related to Alegrowin's post. The idea is use postman to access the IdentityManager Api.
Steps
Open postman and choose the POST verb
Put this as url: https://localhost:44337/ids/connect/token
In header put key = Content-Type and value = application/x-www-form-urlencoded
In the body, choose raw and paste this client_id=postman&client_secret=ClientSecret&grant_type=password&scope=idmgr&username=admin&password=admin
Hit send
After this you are going to receive something like this
{"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg",
"expires_in": 3600,
"token_type": "Bearer"}
Copy the access token and create a GET request
Put this as url: https://localhost:44337/idm/api/users?count=10&start=0
Into the headers put key = Authorization and value = Bearer [paste the token]
Example
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg
Hit send
You should receive something like this
{
"data": {
"items": [
{
"data": {
"subject": "081d965f-1f84-4360-90e4-8f6deac7b9bc",
"username": "alice",
"name": "Alice Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc",
"delete": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc"
}
},
{
"data": {
"subject": "5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"username": "bob",
"name": "Bob Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"delete": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306"
}
},
{
"data": {
"subject": "e3c7fd2b-3942-456f-8871-62e64c351e8c",
"username": "xoetuvm",
"name": "Uylocms Xcyfhpc"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c",
"delete": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c"
}
},
{
"data": {
"subject": "0777d8de-91be-41e2-82ae-01c4576c7aca",
"username": "xdbktbb",
"name": "Qbcqwrg Mypxduu"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca",
"delete": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca"
}
},
{
"data": {
"subject": "10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"username": "acrkkzf",
"name": "Qcmwcha Kdibtke"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"delete": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9"
}
},
{
"data": {
"subject": "5e16f086-a487-4429-b2a6-b05a739e1e71",
"username": "wjxfulk",
"name": "Eihevix Bjzjbwz"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71",
"delete": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71"
}
},
{
"data": {
"subject": "256e23de-410a-461d-92cc-55684de8be6f",
"username": "zputkfb",
"name": "Vhwjjpd Stfpoum"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f",
"delete": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f"
}
},
{
"data": {
"subject": "725cc088-96c3-490d-bc66-a376c8ca34ff",
"username": "teshydj",
"name": "Tirsnex Tdlkfii"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff",
"delete": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff"
}
},
{
"data": {
"subject": "ac773092-e3db-4711-9c95-a2a57c1ff25f",
"username": "blulsuj",
"name": "Puuncng Lbmlcsb"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f",
"delete": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f"
}
},
{
"data": {
"subject": "81f878b1-016e-4fea-9929-54e3b1d55cce",
"username": "yeqwlfy",
"name": "Qtfimdr Sxvgizd"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce",
"delete": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce"
}
}
],
"start": 0,
"count": 10,
"total": 18806,
"filter": null
},
"links": {
"create": {
"href": "https://localhost:44337/idm/api/users",
"meta": [
{
"type": "username",
"name": "Username",
"dataType": 0,
"required": true
},
{
"type": "password",
"name": "Password",
"dataType": 1,
"required": true
},
{
"type": "name",
"name": "Name",
"dataType": 0,
"required": true
},
{
"type": "Age",
"name": "Age",
"dataType": 4,
"required": true
},
{
"type": "IsNice",
"name": "IsNice",
"dataType": 5,
"required": true
},
{
"type": "role.admin",
"name": "Is Administrator",
"dataType": 5,
"required": true
}
]
}
}
}
Kind regards
Daniel