Identityserver4 with ADFS 4.0, cant get Userinfo or Claims - adfs

i have tried to configure my Identityserver4 to use ADFS 4.0 as an external Provider.
I have configured it as followed:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = "60b3d106-d155-4f9f-ba75-84b8078829fa",
AuthenticationScheme = "oidc",
PostLogoutRedirectUri = "http://localhost:5000",
DisplayName = "ADFS TEST Domain",
MetadataAddress = "https://srv2016dc01.test.local/adfs/.well-known/openid-configuration",
SaveTokens = true,
GetClaimsFromUserInfoEndpoint = true
});
Seems to work, as i can login and get a few Claims back:
Claims get back from ADFS
But it doesn't look like that the Userinfo Endpoint will be called...
Otherwise ther schould be more claims, and i can't see a call to the Userinfo Endpoint in the DEbug log of the ADFS Server.
I have also tried to call the Userinfo Endpoint in Code like in this link:
ASP.NET Identity (with IdentityServer4) get external resource oauth access token
But at "await _signInManager.UpdateExternalAuthenticationTokensAsync(info);" i don't get an access_token back, only an id_token...
Does anybody have an working example on Identityserver4 with ADFS 4.0 or at least with any other external OpenIdConnect Server?
Is there any other way to get all the Infos from Userinfo Endpoint?
I need to get the Group Memeberships from the authenticated User as Role Claims, for grant permissions on an WebApi Resource.

If i set "token id_token" as ResponseType Value in the Options, i'll get the tokens!
ResponseType = "code id_token"
If an access_token is available the UserInfo Endpoint will be called.
But now i'll get a 401 Error from the Userinfo Endpoint.
Anyway... This issue is resolved by adding
ResponseType = "code id_token"
to the OpenIdConnectOptions

Related

How to make Owin automatically use refresh token when access token expires

I have an Owin client connected to IdentityServer 4, and am wondering how to get owin to request a new access_token using the refresh token. I can successfully get owin to swap the code given for an access_token, id_token and refresh_token with the following configuration:
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookie"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:5000",
ClientId = "mywebsite",
ClientSecret = "secret",
RedirectUri = "https://localhost:5001/",
ResponseType = "code",
RequireHttpsMetadata = false,
SaveTokens = true,
UseTokenLifetime = true,
SignInAsAuthenticationType = "Cookie",
Scope = "openid profile email offline_access",
RedeemCode = true,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
Console.WriteLine(n);
return System.Threading.Tasks.Task.FromResult(0);
},
TokenResponseReceived = n =>
{
Console.WriteLine(n);
return System.Threading.Tasks.Task.FromResult(0);
}
},
});
}
Firstly, where do I save these tokens to? I can access them all the SecurityTokenValidated callback - should they go into the claims? Database? Memory?
Secondly, I have on my IdentityServer client configuration the access_token lifespan set to 60s, identity_token set to 3600s, and refresh to 30 days (please note the access_token is only this short for testing purposes). So how can I configure Owin to recognize that the access_token has expired and that it needs to go back to identityserver with the refresh_token and get a new one. Answers with example code snippets would be appreciated as my knowledge on all this is very small.
Relevant Info:
IS4 v3
.Net Framework v4.6
Client is set in IS to allow offline access
Take a look at this article:
Automatic Token Management for ASP.NET Core and Worker Services 1.0
Otherwise than that there is no logic in the AddOpenIdConnect(..) handler to deal with renewal of refresh tokens. I think its up to your application to refresh them. Refreshing them in code is not that hard if you have saved the refresh token somewhere safe.
See this question How to use 'refresh_token' in IdentityServer 4?

JWT Authorization policy to Ignore expiration (Lifetime)

I am working with JWT authentication in Asp.net core 3.0. The application is already setup to use JWT authentication and it is working fine. What I am looking for is to have an endpoint to be able to accessed even the auth token is expired (but all the other checks must be validated). I read about the policies and authentication schemes and played with those but it didn't help. How this can be made possible? Any help would be appreciated. TIA
That defeats the whole purpose of the system; why would you want that?
You could technically just increase the lifetime of the token, an example with IdentityServer4:
int tokenLifetime = (int)TimeSpan.FromDays(30).TotalSeconds;
services.AddIdentityServer()
.AddInMemoryClients(new[] {
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("some_secret".Sha256())
},
AllowedScopes = { "your-scope" },
AccessTokenLifetime = tokenLifetime
}
});
Another way is to use refresh tokens to renew your access token.

IdentityServer4 along with Asp.Net 4.5 MVC Client

I am trying to authenticate an existing MVC application built with old Asp.Net (not the core version) with MVC framework.
By following IdentityServer4 and IdentityServer3 examples I have managed to get to a point where my user information is stored in LocalDB using EntityFramework and when I try to access to a restricted page in my client application I get redirected to the Login page provided by the IdentityServer4. However after successful login (based on what I see on the log) It does not redirect to the appropriate page. Address bar stays with something like http://localhost:5000/.... followed by lots of parameters and hashed values. Port 5000 is where I run my identity server and my application is hosted at port 44300 yet I couldn't manage to get back to there.
Has someone faced this kind of issue before or can someone please point me to an example which consists of IdentityServer4 along with a none Core version of Asp.Net.
Edit 1: Implementation Details
Server: IdentityServer4 implementation is almost clone of IdentityServer4 Quickstarts 6-AspNetIdentity.
Config File:
public class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "webapp",
ClientName = "Client WebApp",
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = { "http://localhost:44300/signin-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
AllowOfflineAccess = true
}
};
}
}
Client: Client implementation I am using is a dummy and It originates from IdentityServer3 Client examples "MVC OWIN Client (Hybrid)".
Startup.cs:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
SignInAsAuthenticationType = "Cookies",
ClientSecret = "secret",
Authority = "http://localhost:5000", //ID Server
RedirectUri = "http://localhost:44300/signin-oidc",
ClientId = "webapp",
ResponseType = "id_token code",
Scope = "openid profile",
});
}
}
Log Output: Log output after clicking secured page -> IS Login Page -> Clicking Login.
...
...
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Request path /connect/authorize/login matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Mapping found for endpoint: Authorize, creating handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize/login
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
Start authorize request (after login)
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
User in authorize request: df21b123-d4b6-40ef-beed-e918bdfd56e9
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
Start authorize request protocol validation
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
ValidatedAuthorizeRequest
{
"ClientId": "webapp",
"ClientName": "Client WebApp",
"RedirectUri": "http://localhost:44300/signin-oidc",
"AllowedRedirectUris": [
"http://localhost:44300/signin-oidc"
],
"SubjectId": "df21b123-d4b6-40ef-beed-e918bdfd56e9",
"ResponseType": "code id_token",
"ResponseMode": "form_post",
"GrantType": "hybrid",
"RequestedScopes": "openid profile",
"State": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
"Nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
"SessionId": "61d148313b2a7485dd27e3110ea61fff",
"Raw": {
"client_id": "webapp",
"redirect_uri": "http://localhost:44300/signin-oidc",
"response_mode": "form_post",
"response_type": "id_token code",
"scope": "openid profile",
"state": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
"nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
"x-client-SKU": "ID_NET",
"x-client-ver": "1.0.40306.1554"
}
}
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[#__get_Item_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [e].[Id], [e].[AccessFailedCount], [e].[ConcurrencyStamp], [e].[DefaultDatabaseName], [e].[DefaultDatabaseServer], [e].[Email], [e].[EmailConfirmed], [e].[HierarchyIds], [e].[LockoutEnabled], [e].[LockoutEnd], [e].[NormalizedEmail], [e].[NormalizedUserName], [e].[PasswordHash], [e].[PhoneNumber], [e].[PhoneNumberConfirmed], [e].[SecurityStamp], [e].[TwoFactorEnabled], [e].[UserName]
FROM [AspNetUsers] AS [e]
WHERE [e].[Id] = #__get_Item_0
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
Showing consent: User has not yet consented
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 138.8585ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/consent?returnUrl=%2Fconnect%2Fauthorize%2Fconsent%3Fclient_id%3Dwebapp%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A44300%252Fsignin-oidc%26response_mode%3Dform_post%26response_type%3Did_token%2520code%26scope%3Dopenid%2520profile%26state%3DOpenIdConnect.AuthenticationProperties%253Dm1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk%26nonce%3D636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl%26x-client-SKU%3DID_NET%26x-client-ver%3D1.0.40306.1554
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 32.5652ms 404
Your application running an older version of .NET isn't relevant.
In this video, one of the authors of IdentityServer demonstrates how he was able to connect a WinForm application with IDS4.
The communication to the IDS4 is made through HTTP requests, your client could be anything really as long as it can handle the communication with the IDS4.
I suggest that you open fiddler and monitor the requests to view the parameters passing.
You could also use one of the quickstarts as a base to your IDS, or compare it to your setup to check what's wrong.
From your logs, it is showing that your user has not yet consented to the scopes being requested and so is attempting to navigate to a page on the Identity Server where the user can consent.
`Request starting HTTP/1.1 GET http://localhost:5000/consent?returnUrl=%2Fconnect%2Fauthorize%2Fconsent%3Fclient_id%3Dwebapp%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A44300%252Fsignin-oidc%26response_mode%3Dform_post%26response_type%3Did_token%2520code%26scope%3Dopenid%2520profile%26state%3DOpenIdConnect.AuthenticationProperties%253Dm1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk%26nonce%3D636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl%26x-client-SKU%3DID_NET%26x-client-ver%3D1.0.40306.1554`
This step takes place before redirecting back to your calling website, so I'm guessing you haven't implemented this page on IdSvr yet,

Single Page Application with adal.js and external web api (with AAD authentication)

I have an ASP.NET SPA with a adal-js based authentication, and an ASP.NET Web Api website with Azure Active Directory auth
Both websites are hosted on Azure, on different hostnames, say
https://foo.azurewebsites.com/ and https://fooapi.azurewebsites.com/
The Web Api website auth is configured as
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters() { ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] },
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
}
}
and Main SPA adal.js is initialized as:
var config = {
instance: "https://login.microsoftonline.com/",
tenant: "mytenant",
clientId: "client id of foo registration",
postLogoutRedirectUri: "https://foo.azurewebsites.com/",
cacheLocation: "localStorage"
};
authContext = new AuthenticationContext(config);
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
var errorMessage = authContext.getLoginError();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
// Check if View Requires Authentication
if (!authContext.getCachedUser()) {
authContext.config.redirectUri = window.location.href;
authContext.login();
return;
}
The Tenant is the same for foo and fooapi, the client id is different (one for each app registration).
The authentication flow in the foo web app is performed successfully, but every http request to fooapi returns 401 unauthorized.
How can I make fooapi share the successful authentication of foo ?
Thank you for any hint
You can use the implicit grant flow in AAD so that an ID Token is received and sent in auth header when API call is made. See below links for the details and sample code.
https://azure.microsoft.com/en-gb/documentation/articles/active-directory-authentication-scenarios/#single-page-application-spa
https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp
How you acquire the access token for the web API?
To make sure the request successfully, you need to acquire the token using the resource you config in web API. You can pass the token from here to check whether the aud claim is equal to the value ida:Audience.
And also make sure the token is issued from the tenant you config in web API project since you didn't ignore the tenant verification.
Please configure your web point into endpoints and add it to initialization.
var endpoints = {`enter code here`
"https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932",
};
adalAuthenticationServiceProvider.init(
{
// Config to specify endpoints and similar for your app
tenant: "52d4b072-9470-49fb-8721-bc3a1c9912a1", // Optional by default, it sends common
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e", // Required
//localLoginUrl: "/login", // optional
//redirectUri : "your site", optional
endpoints: endpoints // If you need to send CORS api requests.
},
$httpProvider // pass http provider to inject request interceptor to attach tokens
);

Multiple Authentication Middlewares ASP.NET Core

I am relatively new to the concept of middlewares. I am aware that a middleware calls the next middleware when it completes.
I am trying to authenticate a request using either Google or my Identity Server. The user can login on my mobile app with google or a local account. However, I can't figure out how to use both authentication middlewares. If I pass the id_token for google, it passes on the first middleware (UseJwtBearerAuthentication) but fails on the second one (UseIdentityServerAuthentication). How can I make it so that it doesn't throw error when it actually passes on at least 1 authentication middleware? For example, if it passes on the first middleware, the second middleware is ignored?
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
Authority = "https://accounts.google.com",
Audience = "secret.apps.googleusercontent.com",
TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = true,
ValidIssuer = "accounts.google.com"
},
RequireHttpsMetadata = false
});
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:1000/",
RequireHttpsMetadata = false,
ScopeName = "MyApp.Api"
});
Normally, when an authentication middleware is failed(i don't mean throwing exception), this doesn't affect another successful authentication middleware. Probably your second middleware throws an exception(not a validation failure). First check error message and try to resolve it. If you can't, use AuthenticationFailed event to handle error. In this case your code should be something like below:
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
// ...
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = async (context) =>
{
if (context.Exception is your exception)
{
context.SkipToNextMiddleware();
}
}
}
});
However, for your scenerio i wouldn't choose your way. I would use only identity server endpoint. For signing with google you can configure identity server like below:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = false
});
app.UseGoogleAuthentication(new GoogleOptions
{
AuthenticationScheme = "Google",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
ClientId = "",
ClientSecret = ""
});
app.UseIdentityServer();
Edit
It seems AuthenticationFailed event couldn't be used for IdentityServer4.AccessTokenValidation. I am not sure but if you will use identity server for only jwt token, you can use UseJwtBearerAuthentication for validation.

Resources