I'm following this blog about allowing OpenIDDict to wrap an alternative authentication provider but return a JWT token from OpenIDDict itself:
https://kevinchalet.com/2020/02/18/creating-an-openid-connect-server-proxy-with-openiddict-3-0-s-degraded-mode/
This is really about intercepting the Authorization Code flow rather than the Client Credentials flow, but it provides a good starting point.
Unfortunately it states that "we don't need to override the HandleTokenRequestContext", which is appropriate for the blog but not (as far as I know) for my use case.
I think I need to implement a custom HandleTokenRequestContext but when I do so, the code runs, no errors but the HTTP response is empty. No token is generated.
How should I properly intercept the Client Credentials flow so that I can call out to another provider to validate the credentials, get a result and include that in the custom claims that I need to add to the JWT?
Code below:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContext>(options =>
{
// Configure the context to use an in-memory store - probably not needed?
options.UseInMemoryDatabase(nameof(DbContext));
// Register the entity sets needed by OpenIddict.
options.UseOpenIddict();
});
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<DbContext>();
})
.AddServer(options =>
{
options.SetTokenEndpointUris("/connect/token");
options
//.AllowRefreshTokenFlow()
.AllowClientCredentialsFlow();
// Register the signing and encryption credentials.
// options.AddDevelopmentEncryptionCertificate()
// .AddDevelopmentSigningCertificate();
//Development only
options
.AddEphemeralEncryptionKey()
.AddEphemeralSigningKey()
.DisableAccessTokenEncryption();
// Register scopes (i.e. the modes we can operate in - there may be a better way to do this (different endpoints?)
options.RegisterScopes("normal", "registration");
//TODO: Include Quartz for cleaning up old tokens
options.UseAspNetCore()
.EnableTokenEndpointPassthrough();
options.EnableDegradedMode(); //Activates our custom handlers as the only authentication mechansim, otherwise the workflow attempt to invoke our handler *after* the default ones have already failed
//the request
options.AddEventHandler<ValidateTokenRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
//TODO: Check that the client Id is known
if (!string.Equals(context.ClientId, "client-1", StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidClient,
description: "The specified 'client_id' doesn't match a known Client ID.");
return default;
}
return default;
}));
options.AddEventHandler<HandleTokenRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, OpenIddictConstants.Claims.Name, OpenIddictConstants.Claims.Role);
identity.AddClaim(OpenIddictConstants.Claims.Subject, context.ClientId, OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken);
if (context.Request.Scope == "registration")
{
//TODO: Authenticate against BackOffice system to get it's token so we can add it as a claim
identity.AddClaim("backoffice_token", Guid.NewGuid().ToString(), OpenIddictConstants.Destinations.AccessToken);
}
else
{
//TODO: Authenticate against internal authentication database as normal
}
var cp = new ClaimsPrincipal(identity);
cp.SetScopes(context.Request.GetScopes());
context.Principal = cp;
//This doesn't work either
//context.SignIn(context.Principal);
//ERROR: When this exits the response is empty
return default;
}));
});
//.AddValidation(options =>
//{
// options.UseLocalServer();
// options.UseAspNetCore();
//});
services.AddControllers();
services.AddHostedService<CredentialLoader>();
}
In the end, I got this working with 3 changes:
In the HandleTokenRequestContext:
var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType);
Not sure if this is essential or not. Then remove the
context.Principal = cp;
but re-add the
context.SignIn(context.Principal);
Related
I have an ASP.NET Core 3.1 app that uses Identity to authenticate users. I would like to configure Identity to allow external logins from different providers like Facebook and Twitter.
I have multiple external-login-provider stored in a database. These records can be accessed using IAuthProvider service.
When the app is configured using the ConfigureServices() method, I want to resolve an instance of IAuthProvider to get all available records from the database and then add the needed login-providers.
Below is my code I am struggling on how to resolve IAuthProvider instance while in the ConfigureServices() method. Perhaps there is a better way to configure or defer configure the providers until later but not sure how and where to configure the server.
How can I create an instance of the IAuthProvider and correctly configure the Identity providers?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
options.UseMySql(Configuration.GetConnectionString("MySql"));
});
services.AddScoped<IAuthProvider, AuthProvider>();
// other services
var providers = // Here I somehow need to resolve an instance of IAuthProvider;
AuthenticationBuilder authBuilder = services.AddAuthentication();
foreach (var provider in providers.All())
{
if (provider.Name == ExternalLoginProvider.Facebook)
{
authBuilder.AddFacebook(options =>
{
options.AppId = provider.AppId;
options.AppSecret = provider.Secret;
});
}
if (provider.Name == ExternalLoginProvider.Twitter)
{
authBuilder.AddTwitter(options =>
{
options.ConsumerKey = provider.AppId;
options.ConsumerSecret = provider.Secret;
});
}
// Other providers as needed per the records found in the database
}
}
I see your code has already registered the implementation of IAuthProvider, you can simpply call servcice.GetService() to get an instance of AuthProvider.
I don't get your point of having different authprovider in such a way, according to this document you can add different auth provider in chain like this:
services.AddAuthentication()
.AddMicrosoftAccount(microsoftOptions => { ... })
.AddGoogle(googleOptions => { ... })
.AddTwitter(twitterOptions => { ... })
.AddFacebook(facebookOptions => { ... });
Any reason why adding them seperatly?
Edit:
If you just want to get the instance of IAuthProvider, just try
var serviceProvider = services.BuildServiceProvider();
var provider = serviceProvider.GetService<IAuthProvider>();
I have implemented Aspnet.security.openidconnect.server with .net core 2.1 app. Now I want to test my authorization and for that I am making postman request. If I change the grant type to client_credentials then it works but I want to test complete flow, so I select grant type to Authorzation code and it starts giving error "Could not complete oAuth2.0 login.
Here is the code:
services.AddAuthentication(OAuthValidationDefaults.AuthenticationScheme).AddOAuthValidation()
.AddOpenIdConnectServer(options =>
{
options.AuthorizationEndpointPath = new PathString(AuthorizePath);
// Enable the token endpoint.
options.TokenEndpointPath = new PathString(TokenPath);
options.ApplicationCanDisplayErrors = true;
options.AccessTokenLifetime = TimeSpan.FromMinutes(5);
#if DEBUG
options.AllowInsecureHttp = true;
#endif
options.Provider.OnValidateAuthorizationRequest = context =>
{
if (string.Equals(context.ClientId, Configuration["OpenIdServer:ClientId"], StringComparison.Ordinal))
{
context.Validate(context.RedirectUri);
}
return Task.CompletedTask;
};
// Implement OnValidateTokenRequest to support flows using the token endpoint.
options.Provider.OnValidateTokenRequest = context =>
{
// Reject token requests that don't use grant_type=password or grant_type=refresh_token.
if (!context.Request.IsClientCredentialsGrantType() && !context.Request.IsPasswordGrantType()
&& !context.Request.IsRefreshTokenGrantType())
{
context.Reject(
error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
description: "Only grant_type=password and refresh_token " +
"requests are accepted by this server.");
return Task.CompletedTask;
}
if (string.IsNullOrEmpty(context.ClientId))
{
context.Skip();
return Task.CompletedTask;
}
if (string.Equals(context.ClientId, Configuration["OpenIdServer:ClientId"], StringComparison.Ordinal) &&
string.Equals(context.ClientSecret, Configuration["OpenIdServer:ClientSecret"], StringComparison.Ordinal))
{
context.Validate();
}
return Task.CompletedTask;
};
// Implement OnHandleTokenRequest to support token requests.
options.Provider.OnHandleTokenRequest = context =>
{
// Only handle grant_type=password token requests and let
// the OpenID Connect server handle the other grant types.
if (context.Request.IsClientCredentialsGrantType() || context.Request.IsPasswordGrantType())
{
//var identity = new ClaimsIdentity(context.Scheme.Name,
// OpenIdConnectConstants.Claims.Name,
// OpenIdConnectConstants.Claims.Role);
ClaimsIdentity identity = null;
if (context.Request.IsClientCredentialsGrantType())
{
identity = new ClaimsIdentity(new GenericIdentity(context.Request.ClientId, "Bearer"), context.Request.GetScopes().Select(x => new Claim("urn:oauth:scope", x)));
}
else if (context.Request.IsPasswordGrantType())
{
identity = new ClaimsIdentity(new GenericIdentity(context.Request.Username, "Bearer"), context.Request.GetScopes().Select(x => new Claim("urn:oauth:scope", x)));
}
// Add the mandatory subject/user identifier claim.
identity.AddClaim(OpenIdConnectConstants.Claims.Subject, Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
// By default, claims are not serialized in the access/identity tokens.
// Use the overload taking a "destinations" parameter to make sure
// your claims are correctly inserted in the appropriate tokens.
identity.AddClaim("urn:customclaim", "value",
OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
var ticket = new Microsoft.AspNetCore.Authentication.AuthenticationTicket(
new ClaimsPrincipal(identity),
new Microsoft.AspNetCore.Authentication.AuthenticationProperties(),
context.Scheme.Name);
// Call SetScopes with the list of scopes you want to grant
// (specify offline_access to issue a refresh token).
ticket.SetScopes(
OpenIdConnectConstants.Scopes.Profile,
OpenIdConnectConstants.Scopes.OfflineAccess);
context.Validate(ticket);
}
return Task.CompletedTask;
};
and here is the postman collection:
Now I am not sure that whether the issue is in my code or in postman collection? I think the callback url is creating some issue but I am not sure. Any help?
Update:
By visiing this page https://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-implementing-the-authorization-code-and-implicit-flows/ I have found the issue. I haven't handled authorization code flow in my code but I even don't want to. Is there any way I test my code with Resource owner password? I can't see this grant type in request form. In simple words I want postman to open login screen which is in Controller/Login/Index and I select my ssl Certificate and it generates a token for me?
hello i think that you have to add https://www.getpostman.com/oauth2/callback as the redirect_url in your server config, i don't think that your STS server will return tokens back to a non trusted url. that's why it works from your app but not from Postman
I have been trying to add a parameter in the Login URL. E.g.
services.AddIdentityServer(options =>
{
options.UserInteraction.LoginUrl = "/{culture}/account/login";
});
Is it possible to have such types of parameterized URLs? Also, how would I pass this culture from my (JavaScript) client application? What other options do I have to retain this culture (e.g. as a query string parameter or route data)?
Thanks
After looking into this I managed to hack something that works. I used query string to pass the parameter but you could do it with url.
var paramName = "culture";
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.Request.Path.Value?.Contains("/connect/authorize") ?? false && context.Response.StatusCode == 302 && context.Request.Query[paramName].Count == 1)
{
var location = context.Response.Headers["Location"].ToString();
var tenant = context.Request.Query[paramName].ToString();
var newUrl = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, "tenant", tenant);
context.Response.Redirect(newUrl);
}
});
I send the param from owin UseOpenIdConnectAuthentication and you can add a parameter with
RedirectToIdentityProvider = (a) =>
{
a.ProtocolMessage.Parameters.Add("culture", "en");
return Task.FromResult(0);
},
I am sure you could add the param to all other providers.
NOTE: Don't use this for any secure info just stuff that are cosmetic.
You can pass dynamic values from client application using client oidc externParam.
eg; for oidc-client library(https://www.npmjs.com/package/oidc-client)
// client side code
manager = new UserManager({
authority: localhost:5000 ,
client_id: xxx,
redirect_uri: xx,
response_type: 'code',
scope: 'openid profile .....',
//etc add more settings you need
};);
//initialize connection with identity server
//send settings to authorize endpoint (localhost:5000/connect/authorize)
this.manager.signinRedirect(
{
extraQueryParams: {abc:1} // you can add any number of custom key: value pairs
}
);
but now how to create dynamic options.UserInteraction.LoginUrl based on extraQueryParams received by identity Server at authorize endpoint?
Example:
I have two login pages login1 and login2; not on identity server but at some other url for instance
localhost:4200/login1
localhost:4200/login2
now based on the extraQueryParams received you can add show either of these login pages using AuthorizeInteractionResponseGenerator.
//server side code
//startup.cs
services.AddIdentityServer()
.AddAuthorizeInteractionResponseGenerator<YourCustomAuthorizeEndpointResponseGenerator>();
//make new class
public class YourCustomAuthorizeEndpointResponseGenerator : AuthorizeInteractionResponseGenerator //extending default res generator; you can rewrite also using IAuthorizeInteractionResponseGenerator
{
public YourCustomAuthorizeEndpointResponseGenerator(ISystemClock clock,
ILogger<AuthorizeInteractionResponseGenerator> logger, IConsentService consent,
IProfileService profile,
IHttpContextAccessor httpContextAccessor,
IdentityServerOptions identityServerOptions, // Will be auto injected by identity server; use this to override loginUrl
)
: base(clock, logger, consent, profile)
{
if (httpContextAccessor.HttpContext.Request.QueryString.Value.ToString().Contains("abc=1"))
{
identityServerOptions.UserInteraction.LoginUrl = localhost:4200/login1;
}
else
{
identityServerOptions.UserInteraction.LoginUrl = localhost:4200/login2;
}
}
}
all redirection and callbacks will be taken care by identity server based upon the redirect_uri setting passed from client side.
I'm working on a Xamarin Forms mobile app with .NET backend. I followed this guide and successfully set up custom authentications with one change in Startup.cs:
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
SigningKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"),
ValidAudiences = new[] { Identifiers.Environment.ApiUrl },
ValidIssuers = new[] { Identifiers.Environment.ApiUrl },
TokenHandler = config.GetAppServiceTokenHandler()
});
Without "if (string.IsNullOrEmpty(settings.HostName))". Otherwise I am always getting unauthorized for all requests after login.
Server project:
Auth controller
public class ClubrAuthController : ApiController
{
private readonly ClubrContext dbContext;
private readonly ILoggerService loggerService;
public ClubrAuthController(ILoggerService loggerService)
{
this.loggerService = loggerService;
dbContext = new ClubrContext();
}
public async Task<IHttpActionResult> Post(LoginRequest loginRequest)
{
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.Email == loginRequest.username);
if (user == null)
{
user = await CreateUser(loginRequest);
}
var token = GetAuthenticationTokenForUser(user.Email);
return Ok(new
{
authenticationToken = token.RawData,
user = new { userId = loginRequest.username }
});
}
private JwtSecurityToken GetAuthenticationTokenForUser(string userEmail)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userEmail)
};
var secretKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
var audience = Identifiers.Environment.ApiUrl;
var issuer = Identifiers.Environment.ApiUrl;
var token = AppServiceLoginHandler.CreateToken(
claims,
secretKey,
audience,
issuer,
TimeSpan.FromHours(24)
);
return token;
}
}
Startup.cs
ConfigureMobileAppAuth(app, config, container);
app.UseWebApi(config);
}
private void ConfigureMobileAppAuth(IAppBuilder app, HttpConfiguration config, IContainer container)
{
config.Routes.MapHttpRoute("ClubrAuth", ".auth/login/ClubrAuth", new { controller = "ClubrAuth" });
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
SigningKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"),
ValidAudiences = new[] { Identifiers.Environment.ApiUrl },
ValidIssuers = new[] { Identifiers.Environment.ApiUrl },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
Client project:
MobileServiceUser user = await MobileClient.LoginAsync(loginProvider, jtoken);
Additionally I configured Facebook provider in azure portal like described here.
But it works only when I comment out app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions(){...}); in Startup.cs.
What I am missing to make both types of authentication works at the same time?
Since you have App Service Authentication/Authorization enabled, that will already validate the token. It assumes things about your token structure, such as having the audience and issuer be the same as your app URL (as a default).
app.UseAppServiceAuthentication() will also validate the token, as it is meant for local development. So in your example, the token will be validated twice. Aside from the potential performance impact, this is generally fine. However, that means the tokens must pass validation on both layers, and I suspect that this is not the case, hence the error.
One way to check this is to inspect the tokens themselves. Set a breakpoint in your client app and grab the token you get from LoginAsync(), which will be part of that user object. Then head to a service like http://jwt.io to see what the token contents look like. I suspect that the Facebook token will have a different aud and iss claim than the Identifiers.Environment.ApiUrl you are configuring for app.UseAppServiceAuthentication(), while the custom token probably would match it since you're using that value in your first code snippet.
If that holds true, than you should be in a state where both tokens are failing. The Facebook token would pass the hosted validation but fail on the local middleware, while the custom token would fail the hosted validation but pass the local middleware.
The simplest solution here is to remove app.UseAppServiceAuthentication() when hosting in the cloud. You will also need to make sure that your call to CreateToken() uses the cloud-based URL as the audience and issuer.
For other folks that find this issue
The documentation for custom authentication can be found here.
A general overview of App Service Authentication / Authorization can be found here.
The code you reference is only for local deployments. For Azure deployments, you need to turn on App Service Authentication / Authorization - even if you don't configure an auth provider (which you wouldn't in the case of custom auth).
Check out Chapter 2 of my book - http://aka.ms/zumobook
I am trying to set IdTokenHint when sending the sign out request. In the previous Microsoft.Owin.Security.OpenIdConnect middleware I would be able to set the id_token as a claim in the SecurityTokenValidated method using the SecurityTokenValidated notification by doing something like this:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
...
Notifications = new OpenIdConnectAuthenticationNotifications
{
//Perform claims transformation
SecurityTokenValidated = async notification =>
{
...
notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
},
RedirectToIdentityProvider = async n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
n.ProtocolMessage.IdTokenHint = idTokenHint;
}
}
}
}
With the new middleware Microsoft.AspNetCore.Authentication.OpenIdConnect (in ASP.NET Core RC2) I am having trouble trying to accomplish the same thing. I am assuming I should tap into the Events like so.
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
...
Events = new OpenIdConnectEvents()
{
OnTokenValidated = context =>
{
...
context.SecurityToken.Payload.AddClaim(new Claim("id_token", context.ProtocolMessage.IdToken));
},
OnRedirectToIdentityProviderForSignOut = context =>
{
var idTokenHint = context.HttpContext.User.FindFirst("id_token").Value;
context.ProtocolMessage.IdTokenHint = idTokenHint;
}
}
}
The problem I'm seeing is that the claims do not remain on the SecurityToken and don't get set on the HttpContext.User. What am I missing?
Regarding your code above, at least in version 2.1 of ASP.NET Core, the ID token can be accessed via context.Properties.GetTokenValue(...) (rather than as a user claim).
And, as Brock Allen said in a comment to your question, the OpenIdConnectHandler will automatically include the idTokenHint on sign out. However, and this bit me for a few hours today, when the handler processes the sign-in callback, it will only save the tokens for later if OpenIdConnectOptions.SaveTokens is set to true. The default is false, i.e., the tokens are no longer available when you do the sign-out.
So, if SaveTokens is true, the handler will automatically include the idTokenHint on logout, and you can also manually access the id token via context.Properties.GetTokenValue(...).