set MaxInactiveTime in Azure is not working - azure

I set AzureADPolicy by
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:10:00","MaxInactiveTime":"00:10:30","MaxAgeSessionSingleFactor":"00:11:00"}}') -DisplayName "PolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
and AccessTokenLifetime is work, my access token expires in 600,
buy MaxInactiveTime is not work, I also can get access token after 15 minute
Thanks for answer

I believe that you are using confidential clients (Azure AD application is registered as a "Web" application) rather than public clients ((Azure AD application is registered as a "Public client" application)).
MaxInactiveTime is only available for public clients app. It cannot be changed by using policy in confidential clients app.
See more details here.

Related

Setting Token lifetime in Azure ADB2C

we are using Azure ADB2C with grant type as client credentials. We are sharing clientid, secret with customers to consume our APIs. We don't have any user flow created as it not required.
Is there anyway we can change the token lifetime to 15 min (default is 60min)
Based on your description, I understand that you are using AAD client credentials flow because B2C doesn't support client credentials flow.
If so, your customer doesn't use the B2C feature.
You can configure token lifetime policies for your AAD feature.
$policy = New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:15:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"

How to Connect-AzAccount in Powershell Core (without prompt)?

I did see this q/a: Connect-AzAccount without prompt
But when I tried the accepted answer, I get the following error:
[6/12/2020 12:36:20 AM] ERROR: Connect-AzAccount : Username + Password authentication is not supported in PowerShell Core. Please use device code authentication for interactive log in, or Service Principal authentication for script log in.
So I went to example 3 of the Connect-AzAccount documentation which specifies the "Service Principal" authentication method, so I mix the two because the suggested vanilla Get-Credential triggers another interactive session. So here's the script now:
$User = "myemail#gmail.com"
$PWord = ConvertTo-SecureString -String "**********" -AsPlainText -Force
$tenant = "f*********************************"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
# $Credential = Get-Credential
Connect-AzAccount -Credential $Credential -Tenant $tenant -ServicePrincipal
which brings my next error: [6/12/2020 12:45:45 AM] ERROR: Connect-AzAccount : AADSTS700016: Application with identifier 'myemail' was not found in the directory 'f*********************************'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
I'm really confused at this point because all I have done at this point in Azure is:
Create a new Azure account
Provision an Azure API Management instance through the UI (which btw, takes like 20 minutes)
Try the above code to connect to Azure inside of a Powershell Azure Function locally.
I think something is wrong with the information I've provided or how I've configured something.
$User is the email I signed up to Azure with.
$PWord is my Azure password
$tenant is the first thing I saw when I opened Azure AD:
What's wrong with how I'm trying to connect to Azure through Powershell Core?
Based on Example 3, it asks for entering your application ID for the username and service principal secret as the password.
So you need to create a service principal at first. And then use its application ID and client secret as the credential.
$User = "{application id}"
$PWord = ConvertTo-SecureString -String "{client secret}" -AsPlainText -Force
I don't like Azure documentation. It gives off a very different vibe from GCP and feels much less beginner friendly.
With that said, they did have some kind of write-up that addresses my issue of creating a service principal and using it to authenticate.
I actually ended up just finding a video (and I never do this) because I wanted to skip past all the technical jargon and just create the darn service principal.
It's not even intuitive - it's like Microsoft could have added a button in AZ AD or IAM that said "Create Service Principal" but no, you have to go to a bunch of other pages that say nothing about service principals. You'll see:
In Azure Portal, navigate to the App Registrations page in Azure Active Directory. What an "app registration" has to do with a service principal, I couldn't tell you. I also couldn't tell you what a service principal is, but I'd imagine it has something to do with service accounts.
Make a New Registration and give it some sort of name to describe what the scope of this service principal will entail. Like normal service account naming conventions. I don't think the account type matters but I chose Multitenant. Redirect URL has nothing to do with service principals, and honestly makes it all the more confusing. I would never associate service accounts with any kind of redirect url, but here we are.
You're going to arrive at a page with Display Name (the name of the service principal you gave it in step 2), Application (client) ID (this is actually your service account username, which is imo non-intuitive), and Object ID (I have no idea what this is but I never needed to use it.
Guess what, you have only created 1/3 of your service account. It doesn't even have a password yet. Within your created app registration, there's a Certificates & Secrets page. On that page, you want to add a new client secret. For my description I just put my service principal "display name". I don't think that was necessary because this client secret is within the scope of the app registration, so even if I named it "poop" I could reasonably assume what it was for. Azure will generate a nuanced client secret and display it, but not warn you that this is the only time you will be able to see the key. Copy it. This is, in normal people talk, your service principal password.
For the last step, you need to get out of dodge, I mean Azure AD. Navigate to your Subscriptions page and click on your active subcription. For some reason IAM is here, so click on that. At this point, your service principal has a username and password, but no actual permissions - you have to configure that manually too. Click Add -> Add Role Assignment. For role, you should do your research but if it's not serious Contributor is probably a safe bet. It has read/write but it doesn't supersede Owner. Make sure you're assigning access to a service principal, and search for its display name. Save.
With all of that done, Connect-AzAccount finally worked.

Certificate added via New-AzureADApplicationKeyCredential not appearing in Azure AD discovery endpoint

I'm adding a new certificate to an existing App Registration in Azure AD using the following command:
New-AzureADApplicationKeyCredential -ObjectId $AppObjectId -CustomKeyIdentifier $base64Thumbprint -Type AsymmetricX509Cert -Usage Verify -Value $base64Value -StartDate $cer.GetEffectiveDateString() -EndDate $validTo
This works OK and I can see the cert added in the Portal.
Should this certificate not also be visible via https://login.microsoftonline.com/{tenant}/discovery/keys?appid={Application(client)ID}
I've also tried adding the certificate info via Set-AzureADApplication & directly via the Portal. Each time I can see the certificate under "Certificates and Secrets" as well as in the App Manifest. No matter what I do I can't see the public cert in the JWKS endpoint.
My assumption on this comes from the following:
https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens
"If your app has custom signing keys as a result of using the claims-mapping feature, you must append an appid query parameter containing the app ID to get a jwks_uri pointing to your app's signing key information, which should be used for validation. For example: https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration?appid=6731de76-14a6-49ae-97bc-6eba6914391e contains a jwks_uri of https://login.microsoftonline.com/{tenant}/discovery/keys?appid=6731de76-14a6-49ae-97bc-6eba6914391e."
Any help would be much appreciated.
As far as I understand, the keys you add to the app are only used for authenticating your app to Azure AD.
Thus there is no need to advertise those keys in the public endpoint, as only Azure AD itself needs to use those public keys to verify assertions sent by your app.
Seems like you set the keyusage to Verify. If you want to use it for signing the token you need to set it to Sign and use a symmetric key:
New-AzureADApplicationKeyCredential -ObjectId $AppId -CustomKeyIdentifier "Test" -StartDate "11/7/2016" -Type "Symmetric" -Usage "Sign" -Value "123"

Configuring Azure AAD token lifetime to 10mins using powershell doesn't work

I have followed below article for configuring azure aad token lifetime to 10mins
How can I configure the expiration time of an Azure AD access token (using ADAL)?
I have used command below for assigning policy to app
Add-AzureADApplicationPolicy -Id <ObjectId of the AAD Application> -RefObjectId <ObjectId of the Policy>
Policy created but not reflected on new tokens created. Token expiry still showing as 1 hour for new tokens.
As AdminOfThings said, this policy is applied to the web API. When the native app requests the web API as a resource, this policy is applied.
And you could try to set -IsOrganizationDefault as true to create a strict policy for a web API.
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:10:00","MaxAgeSessionSingleFactor":"00:10:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
You should also check to see if a default policy exists too, as long as it is not overridden by a policy with a higher priority.

Azure REST api security

I am searching for feature like AAD User wise roles/policies for specific APIs in API Management Service.
AWS is offering rule based access control. For example, we can assign specific api (of API Gateway) access to specific IAM user using Role/Policies.
Does Azure is offering service like this ?
For example, i have added 20 api's (5 GET + 5 POST + 5 PUT + 5 DELETE) in Azure API management service.
Can i assign specific method (ex. GET) api access to specific user?
One option to achieve this (without code, just configuration) is to use Azure Active Directory (AAD) Application Roles.
First, you need to create an AAD application representing your Web API. Go to AAD > App Registrations and register there a Web App / Web API. Then edit its manifest to add a role, i.e.:
"appRoles": [
{
"allowedMemberTypes": [
"Application",
"User"
],
"displayName": "Allow HTTP GET",
"id": "9cc5ee71-3d7d-4060-8b7f-e734f3917e71",
"isEnabled": true,
"description": "Allow HTTP GET requests",
"value": "AllowGET"
}
],
You can add different roles for the different methods your API has.
Then go to AAD > Enterprise Applications, find the application you just created, and:
In Properties, select "User assignment required" > Yes
In Users and Groups, add the users you want to allow access to the role you created before ("Allow HTTP Get").
Now go to the API Management service > APIs > find your API / Method and edit Inbound processing. Under Code View, add a ValidateJWT policy to validate the AAD tokens (make sure to configure your AAD tenant name and to configure the audience GUID which is the application ID of your Web API (the one that you registered in AAD at the beginning):
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
<openid-config url="https://login.microsoftonline.com/TENANT.onmicrosoft.com/.well-known/openid-configuration" />
<audiences>
<audience>53a81160-e4c9-40ba-aeef-6bb99ad6b4b3</audience>
</audiences>
<required-claims>
<claim name="roles" match="all">
<value>AllowGET</value>
</claim>
</required-claims>
</validate-jwt>
Notice that under required-claims is the role claim (AllowGET) you configured before, in the application manifest.
Now you can test. If you want to test through the APIM Developer Console you should follow the instructions here Protect an API by using OAuth 2.0 with Azure Active Directory and API Management.
Or you can also test by just using a simple PowerShell script like the below. If you use this script, first you need to register another AAD application, this time representing the script (a "native client"). Go to AAD > App Registrations and register a Native Client. Under Settings > Permissions, add a delegated permission so this application can call the Web API:
PowerShell script: (review the code and make sure to replace the parameters and the URL of your API, and to add the path to the ADAL library "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" which is used to simplify the token adquisition)
add-type -path "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$clientId = "NATIVE APPLICATION AAD AAP ID"
$redirectUri = "http://NATIVE APPLICATION AAD REDIRECT URI"
$resourceAppIdURI = "WEB API APP ID"
$authority = "https://login.windows.net/TENANT.onmicrosoft.com"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$promptBehavior=new-object Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters([Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
$userId = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier]::AnyUser
$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI, $clientId, $redirectUri, $promptBehavior, $userId, $extraQueryParameters)
$authHeader = #{
'Accept'='application/json'
'Content-Type'='application/json'
'Authorization'=$authResult.result.CreateAuthorizationHeader()
'Ocp-Apim-Subscription-Key'='APIM SUBSCRIPTION KEY'
'Ocp-Apim-Trace'='true'
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -Uri "https://yourapimanager.azure-api.net/posts" -Headers $authHeader -Method Get -Verbose

Resources