DX20807: Unable to retrieve document from: ‘[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.] site:stackoverflow.com

Hi everyone,

I ran into the following error today while implementing Azure AD B2C:

DX20807: Unable to retrieve document from: ‘[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.%5D site:stackoverflow.com

There are a lot of different solutions to this error posted on Stackoverflow, Github, etc but without anything else to go on it’s pretty hard to narrow down the cause. This is where the ShowPII property comes in handy:

….
var resultJson = configuration.GetSection(“AzureAdB2cConfiguration”).Value;
var azureConfig = JsonConvert.DeserializeObject(resultJson);

Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; // TODO: This should be removed in production and the authority url changed to https

jwtOptions.RequireHttpsMetadata = false; // TODO: This should be removed in production and the authority url changed to https
jwtOptions.Authority = azureConfig.Authority;
jwtOptions.Audience = azureConfig.AppClientId;
jwtOptions.Events = new JwtBearerEvents {
OnAuthenticationFailed = AuthenticationFailed,
};


static Task AuthenticationFailed(AuthenticationFailedContext arg)
{
// For debugging purposes only!
var s = $”AuthenticationFailed: {arg.Exception.Message}”;
arg.Response.ContentLength = s.Length;

System.Diagnostics.Debugger.Break();
return arg.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(s), 0, s.Length);
}

Simply set Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII to true while configuration your authentication and the full internal error will be shown instead of the vague PII message.

In my case this turned out to be an issue with the construction of my authority url.

Cheers,
Chris

Return URL is missing path – Azure AD B2C

Hi everyone,

Just a small issue I’ve hit while implementing Azure AD B2C. After logging in Azure has been routing me to the base path instead of including the controller.

The solution to this turned out to be pretty straight-forward. All URLS apparently need to be including in the reply URLs of your Azure AD B2C application.

Just add a new row with the entire url to yours and it should start working immediately.

Thanks,
Chris

Cognito Auth with AWS SAM

Hi everyone,

I’ve spent today implementing Cognito with AWS SAM and it took quite a while to work out what needed to be done – unfortunately there’s a lot of conflicting doco out there. Posting a sample template just in case it’s able to help anyone else out.

The first thing to do is to explicitly define you rest API. By default AWS SAM will generate one with a default logical id of ServerlessRestApi. You’ll need to override this:

Resources:
  # See links for more info
  # Referencing cognito authorizer: https://github.com/awslabs/serverless-application-model/issues/512#issuecomment-411284092
  # Logical id is auto generated: https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  # Sample template.yml: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml
  MyCustomApi:
    Type: "AWS::Serverless::Api"
    Properties:
      StageName: Prod
      Auth: # We will eventually define other auth options here such as Usage Plans/Api Keys, AWS_IAM, and Resource Policies
        DefaultAuthorizer: MyCustomCognitoAuthorizer
        Authorizers:
          MyCustomCognitoAuthorizer:
            UserPoolArn: !GetAtt MyCustomCognitoUserPool.Arn # Can be a string, or array
            # Identity: # Optional
              # Header: ... # Optional; Default: Authorization
              # ValidationExpression: ...  # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?

You’ll also need to create a user pool and client:

# Creating a cognito user pool - https://github.com/awslabs/serverless-application-model/blob/master/examples/2016-10-31/api_cognito_auth/template.yaml
  MyCustomCognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Ref CognitoUserPoolName
      # LambdaConfig:
        # PreSignUp: !GetAtt PreSignupLambdaFunction.Arn
      Policies:
        PasswordPolicy:
          MinimumLength: 8
      UsernameAttributes:
        - email
      Schema:
        - AttributeDataType: String
          Name: email
          Required: false

  MyCustomCognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref MyCustomCognitoUserPool
      ClientName: !Ref CognitoUserPoolClientName
      GenerateSecret: false

You then add the api id and the auth attribute to each of your function properties. If you’ve used the default authorizer property when defining the associated api you can override it by using authorizer: none.

GetBreedFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: breed.getBreedHandler
      Policies: arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess
      Runtime: nodejs8.10
      Environment:
        Variables:
          TABLE_CAT_BREED: !Ref CatBreedTable
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /breed/{breedId}
            Method: get
            RestApiId: !Ref MyCustomCustomApi
            Auth:
              Authorizer: NONE

Hopefully that’s able to help you out. If you run into any trouble I found the following link pretty useful: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml

Include UserId in Login Response (Token) – Web API 2

Hi everyone,

A quick post on how to include the user’s id in your login response when using Web API 2.

The default response to the /Token request is as follows:

{
“access_token”: “xxxxxxxxxxxxx_xxxx”,
“token_type”: “bearer”,
“expires_in”: 1209599,
“userName”: “test@test.com”,
“.issued”: “Mon, 23 Apr 2018 06:08:03 GMT”,
“.expires”: “Mon, 07 May 2018 06:08:03 GMT”
}

Once the changes below have been made the response will include a userId field:

{
“access_token”: “xxxxxxxxxxxxx_xxxx”,
“token_type”: “bearer”,
“expires_in”: 1209599,
“userName”: “test@test.com”,
“.issued”: “Mon, 23 Apr 2018 06:08:03 GMT”,
“.expires”: “Mon, 07 May 2018 06:08:03 GMT”,
“userId”: “xxxxxxx”
}

There are three very small changes required in order to add this functionality.

First, add an additional argument to CreateProperties in ApplicationOAuthProvider.cs

public static AuthenticationProperties CreateProperties(string userName, string userId)
{
IDictionary data = new Dictionary
{
{ "userName", userName },
// Add
{ "userId", userId }
};
return new AuthenticationProperties(data);
}

Pass userId to CreateProperties in ApplicationOauthProvider.

// ApplicationOAuthProvider.cs > GrantResourceOwnerCredentials
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);

// Add user id
AuthenticationProperties properties = CreateProperties(user.UserName, user.Id);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);

Pass userId to CreateProperties in AccountController.

// AccountController.cs > GetExternalLogin
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);

// Add userid
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, user.Id);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

Unsupported_Grant_Type – MVC Web Api (error)

Hi everyone,

I ran into the following error while attempting to authenticate using .NET Web Api:

POST http://localhost:63720/Token HTTP/1.1
Host: localhost:63720
Content-Type: application/json
Content-Length: 0
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8
Date: Mon, 16 Apr 2018 14:18:06 GMT
Content-Length: 34

{“error”:”unsupported_grant_type”}

This one was pretty straight forward. Ensure that have the correct content-type:

Content-Type: application/x-www-form-urlencoded

And finally, ensure that you provide a grant type in the request body:

grant_type=password&username=test_username&password=test_password

Thanks to the following stackoverflow post for the info: https://stackoverflow.com/a/29261024/522859

Change Default MVC5 Password Complexity Requirements – Passwords must have at least one non letter or digit character. Passwords must have at least one digit (‘0’-‘9’). Passwords must have at least one uppercase (‘A’-‘Z’)

Hey everyone,

I’ve started on a new MVC5 project and came across the following error message while trying to register a new user:

Passwords must have at least one non letter or digit character.
Passwords must have at least one digit (‘0’-‘9’).
Passwords must have at least one uppercase (‘A’-‘Z’)

While having a secure password is obviously important, I felt that most users would probably find these requirements a little extreme. After a bit of Googling I came across a StackOverflow post that mentioned a config class that you can use to edit these settings:

// App_Start > IdentityConfig.cs

...

// Configure validation logic for usernames
            manager.UserValidator = new UserValidator(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

...

Twitter Authentication 401 Unauthorized – MVC4/5

Hey everyone,

Just testing out twitter authentication and ran into the following error:

Response Status code does not indicate success: 401 (Unauthorized).

To fix this, all you’ve got to do is go to you Twitter App settings and:
– Add a callback url (doesn’t have to be real)
– Check the ExternalLoginConfirmationViewModel checkbox

Unable to Find GoogleOAuth2AuthenticationOptions – MVC4/5

Hey everyone,

I was following the guide provided via the startup.auth.cs link on how to add Google authentication to your app. The problem I hit was that the example types used weren’t available, specifically GoogleOAuth2AuthenticationOptions.

Thankfully the fix fix for this was pretty easy, simply update OWIN via NuGet:

– Right click on your project
– Go to Manage NuGet Packages
– Click on the updates drop down
– Search for OWIN
– Update all of the relevant options

Thanks to this Stackoverflow post for the solution: http://stackoverflow.com/a/23606431/522859