I am trying to get access token for microsoft graph api as well as One note while SSO login.
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
Authority = AuthenticationConfig.Authority,
ClientId = AuthenticationConfig.ClientId,
RedirectUri = AuthenticationConfig.RedirectUri,
PostLogoutRedirectUri = AuthenticationConfig.RedirectUri,
Scope = AuthenticationConfig.BasicSignInScopes + " Files.Read Files.Read.All Files.Read.Selected Files.ReadWrite Files.ReadWrite.All Files.ReadWrite.AppFolder Files.ReadWrite.Selected Notes.Create Notes.Read Notes.Read.All Notes.ReadWrite Notes.ReadWrite.All Notes.ReadWrite.CreatedByApp User.Read User.Read.All", // a basic set of permissions for user sign in & profile access "openid profile offline_access"
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
// In a real application you would use IssuerValidator for additional checks, like making sure the user's organization has signed up for your app.
//IssuerValidator = (issuer, token, tvp) =>
//{
// if(mycustomtenantvalidation(issuer))
// return issuer;
// else
// throw new securitytokeninvalidissuerexception("invalid issuer");
// },
//NameClaimType = "name",
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed,
},
// Handling SameSite cookie according to https://learn.microsoft.com/en-us/aspnet/samesite/owin-samesite
CookieManager = new SameSiteCookieManager(
new SystemWebCookieManager())
The access token I am getting is working for One drive only. For one note getting request does not contain valid access token
Getting Access Token:-
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
// Upon successful sign in, get the access token & cache it using MSAL
IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "Files.Read Files.Read.All Files.Read.Selected Files.ReadWrite Files.ReadWrite.All Files.ReadWrite.AppFolder Files.ReadWrite.Selected Notes.Create Notes.Read Notes.Read.All Notes.ReadWrite Notes.ReadWrite.All Notes.ReadWrite.CreatedByApp User.Read User.Read.All" }, context.Code).ExecuteAsync();
var code = context.Code;
}
I have checked that we need to pass the resource id for one note while login. But I am not getting where to pass that.
Related
We have just upgraded our web app to .NET 5 and IdentityServer4 to V4, also we switched from hybrid flow to code + PKCE. The client is set to an access token type of reference, also the client uses bearer tokens for an internal API as well as cookies for the main website.
When we deploy to our internal development server (IIS 8.5) or to Azure App Services randomly when we ask for the access token (reference) we are returned an access token (JWT) instead. We did use the httpContext.GetTokenAsync() method but then replaced it with the identitymodel.aspnetcore GetUserAccessTokenAsync() method but it still returns a JWT Token.
I have validated the JWT tokens contents and they are the relevant user and their claims. I have also checked the persisted grant table and the reference token entered in there specifies it as a JWT instead of Reference.
The only way to rectify the situation is
Stop the website and identityserver
Clear the cookies in the browser
Delete all entries in the persisted grants table
Recycle the app pools
Start the identity server and then perform a login
Start the website which the login is for and suddenly we get a reference access token again
Identity Server Client Config
AllowedGrantTypes =
{
GrantType.AuthorizationCode,
"exchange_reference_token"
},
AccessTokenType = AccessTokenType.Reference,
AccessTokenLifetime = 86400,
RequireConsent = false,
AllowAccessTokensViaBrowser = true,
ClientSecrets =
{
new Secret("*******)
},
RedirectUris = { $"{client}/signin-oidc" },
PostLogoutRedirectUris = { $"{client}/signout-callback-oidc" },
FrontChannelLogoutUri = $"{client}/signout-oidc",
AllowedCorsOrigins = { client },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"roles",
"API1",
"API2",
"API3",
"Signalr"
},
UpdateAccessTokenClaimsOnRefresh = true,
AllowOfflineAccess = true
I've found out what is causing the issue. We are using signalr in the website and we are having to use the exchange_reference_token, however in the exchange code it forces the access token to JWT, this then gets inserted in the persisted grant table causing any future request to return JWT instead of of reference access token
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
var referenceToken = context.Request.Raw.Get("token");
if (referenceToken == null)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Missing Reference Token");
}
var result = await _validator.ValidateAccessTokenAsync(referenceToken);
if (result == null)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Invalid Reference Token");
}
// Generate the JWT as if it was for the reference token's client
context.Request.Client.AccessTokenType = AccessTokenType.Jwt;
var sub = result.Claims.FirstOrDefault(c => c.Type == "sub").Value;
context.Result = new GrantValidationResult(sub, GrantType, result.Claims);
}
I'm Fetching access token in ASP.NET MVC application using Open ID connect hybrid flow. And using this access token to invoke Power BI Rest APIs. However once the access token has expired, the REST API calls fails for obvious reasons.
My question is How do I get the new access token/refresh without pushing user for interactive login?
public void ConfigureAuth(IAppBuilder app)
{
try
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = redirectUri,
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
},
AuthorizationCodeReceived = OnAuthorizationCodeCallback
}
});
app.UseStageMarker(PipelineStage.Authenticate);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private static async Task OnAuthorizationCodeCallback(AuthorizationCodeReceivedNotification context)
{
var appConfidential = ConfidentialClientApplicationBuilder.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
string powerBiPermissionApi = "https://analysis.windows.net/powerbi/api/";
string[] ReadUserWorkspaces = new string[] {
powerBiPermissionApi + "Workspace.Read.All",
powerBiPermissionApi + "Report.Read.All",
powerBiPermissionApi + "Dashboard.Read.All",
powerBiPermissionApi + "Dataset.Read.All"
};
var authResult = await appConfidential.AcquireTokenByAuthorizationCode(ReadUserWorkspaces, context.Code).ExecuteAsync();
ClaimsIdentity userClaims = context.AuthenticationTicket.Identity;
userClaims.AddClaim(new Claim("Access_Token", authResult.AccessToken));
}
With Azure Active Directory, we may specify our own custom timeout for measured days / Decouple the session length from the token validity.
One of the approaches I found is to separate the session duration from the original token's expiration times. By supplying the following option to the OIDC Middleware, you can tell it to stop controlling this aspect in the cookie Middleware:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
...
UseTokenLifetime = false,
}
);
The cookie Middleware will now follow whatever settings you provide in the cookie Middleware parameters if UseTokenLifetime is set to false.
Alternatively, we can use an iFrame from a page that updates every 5 minutes.
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" id="refreshAuthenticationIframe" src="#Url.Action("CheckSessionTimeout", "Home", new { area = "" })" style="display:none;"></iframe>
You find additional details through this Thread.
REFERENCES:
Controlling a Web App’s session duration – CloudIdentity
Solved: How to use Power BI Rest API without GUI authentic... - Microsoft Power BI Community
We have a ASP.NET application that uses Microsoft's common login to log in the users, then it redirects back to our web application (in Azure). The authentication is connected to Azure Active Directories. It is a multi-tenant application with multiple Azure ADs. When Microsoft redirects back to our site, we use the information to create a cookie that is used for the web calls. In addition, the call back returns a user code that we use to get a token. This is used as authentication against our API controllers.
This has been working for a long time. Now, however, we need to integrate with another 3rd party portal that will launch our product. They will be using SAML for SSO. They are not integrated with Azure AD. So, the idea is that we validate the users via the SAML assertions. That will contain the username that we then want to "log in" with.
I can create the cookie off of this information and that works fine with our web controller calls. However, since I'm not getting a callback from Azure AD, I don't have the token for the API calls. I have tried to call Azure AD to authenticate the applications, but that does seem to satisfy the API Controller's authorization. Specifically, RequestContext.Principal.Identity doesn't seem to be set with this pattern.
I have set the cookie authentication with this code:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
var cookieOptions = new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromDays(14),
SlidingExpiration = true,
LoginPath = new PathString("/home/login"),
AuthenticationType = "ApplicationCookie",
AuthenticationMode = AuthenticationMode.Active,
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.Always,
CookieSameSite = SameSiteMode.Lax,
};
// Forms/Cookie Authentication
app.UseCookieAuthentication(cookieOptions);
And I left the bearer token authentication code like this:
// Bearer Token Authentication used for API access
BearerAuthenticationOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = <application tenant id>,
AuthenticationType = OAuthDefaults.AuthenticationType,
// Disable Issuer validation. We'll validate the Isuuer in the ClaimsAuthorizationFilter.
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = <resource id>,
ValidateIssuer = false
},
};
app.UseWindowsAzureActiveDirectoryBearerAuthentication(BearerAuthenticationOptions);
The code that handles the Azure AD auth (that the SAML login should replace) is:
var openIdConnectOptions = new OpenIdConnectAuthenticationOptions { ClientId = <ClientId>, Authority = "https://login.windows.net/common/", // setting this to false uses the cookie expiration instead UseTokenLifetime = false, TokenValidationParameters = new TokenValidationParameters { // we'll validate Issuer on the SecurityTokenValidated notification below ValidateIssuer = false },
Notifications = new OpenIdConnectAuthenticationNotifications { // An AAD auth token is validated and we have a Claims Identity SecurityTokenValidated = context => { ... additional validation is performed here...
return Task.FromResult(0); },
//the user has just signed in to the external auth provider (AAD) and then were redirected here // with an access code that we can use to turn around and acquire an auth token AuthorizationCodeReceived = context => { var code = context.Code; var identity = context.AuthenticationTicket.Identity;
var appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; // causes the retreived API token to be cached for later use TokenService.GetUserLevelTokenFromAccessCode(new HttpUserSessionWithClaimsId(identity), code, <ApiResourceId>, new Uri(appBaseUrl));
return Task.FromResult(0); }, // We are about to redirect to the identity provider (AAD) RedirectToIdentityProvider = context => { // This ensures that the address used for sign in and sign out is picked up dynamically from the request // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand. var appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
context.HandleResponse();
return Task.FromResult(0); }, // Something went wrong during this auth process AuthenticationFailed = context => { if (context.Exception is Microsoft.IdentityModel.Protocols.OpenIdConnect
.OpenIdConnectProtocolInvalidNonceException) {
//This is a message we can't do anything about, so we want to ignore it.
Log.Info("AuthenticationFailed in OpenIdConnectAuthentication middleware", context.Exception); } else {
Log.Error("AuthenticationFailed in OpenIdConnectAuthentication middleware",
context.Exception); }
// IDX10205 == Tenant validation failed var message = (context.Exception.Message.StartsWith("IDX10205"))
? InvalidTenantMessage
: GenericErrorMessage;
context.OwinContext.Response.Redirect("/?Error=" + Uri.EscapeDataString(message)); context.HandleResponse(); // Suppress the exception return Task.FromResult(0); }, MessageReceived = context => { if (!string.IsNullOrWhiteSpace(context.ProtocolMessage.Error)) {
// AADSTS65004 == user did not grant access in OAuth flow
Log.Error("MessageReceived containing error in OpenIdConnectAuthentication middleware. \nError: {0}\nDescription: {1}"
.FormatWith(context.ProtocolMessage.Error, context.ProtocolMessage.ErrorDescription));
//context.OwinContext.Response.Redirect("/");
//context.HandleResponse(); // Suppress the exception } return Task.FromResult(0); } } };
app.UseOpenIdConnectAuthentication(openIdConnectOptions);
Any help would be greatly appreciated.
Turns out the value I put for AuthenticationType in the cookie was causing the disconnect. Once I fixed that, the data came through. So closing his question.
Thanks.
Im trying Azure AD B2C and I've added Google and Microsoft Identity Providers through Azure Portal.
When i try to login with Microsoft OR Google IP, i always receive following error message in the OnAuthenticationFailed-Handler:
AADB2C99002: User does not exist. Please sign up before you can sign in.
But when i'm using the "Local Account SignIn" Provided by Azure B2C everything is working fine. Do i missing something in my configuration ?
The following code snippet shows my OWIN Configuration.
private void ConfigureAuthentication(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
{
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = clientId,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
SecurityTokenValidated = context => {
return null;
}
},
Scope = "openid offline_access",
// The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
// endpoints from the OpenID Connect metadata endpoint. It is included in the PolicyAuthHelpers folder.
ConfigurationManager = new PolicyConfigurationManager(
String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, "/v2.0", OIDCMetadataSuffix),
new string[] { SignUpPolicyId, SignInPolicyId, ProfilePolicyId }),
// This piece is optional - it is used for displaying the user's name in the navigation bar.
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "name",
},
};
app.UseOpenIdConnectAuthentication(options);
}
// This notification can be used to manipulate the OIDC request before it is sent. Here we use it to send the correct policy.
private async Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
PolicyConfigurationManager mgr = notification.Options.ConfigurationManager as PolicyConfigurationManager;
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
OpenIdConnectConfiguration config = await mgr.GetConfigurationByPolicyAsync(CancellationToken.None, notification.OwinContext.Authentication.AuthenticationResponseRevoke.Properties.Dictionary[AzureB2C.PolicyKey]);
notification.ProtocolMessage.IssuerAddress = config.EndSessionEndpoint;
}
else
{
OpenIdConnectConfiguration config = await mgr.GetConfigurationByPolicyAsync(CancellationToken.None, notification.OwinContext.Authentication.AuthenticationResponseChallenge.Properties.Dictionary[AzureB2C.PolicyKey]);
notification.ProtocolMessage.IssuerAddress = config.AuthorizationEndpoint;
}
}
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// The user's objectId is extracted from the claims provided in the id_token, and used to cache tokens in ADAL
// The authority is constructed by appending your B2C directory's name to "https://login.microsoftonline.com/"
// The client credential is where you provide your application secret, and is used to authenticate the application to Azure AD
string userObjectID = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, string.Empty, string.Empty);
ClientCredential credential = new ClientCredential(clientId, clientSecret);
// We don't care which policy is used to access the TaskService, so let's use the most recent policy
string mostRecentPolicy = notification.AuthenticationTicket.Identity.FindFirst(AzureB2C.AcrClaimType).Value;
// The Authentication Context is ADAL's primary class, which represents your connection to your B2C directory
// ADAL uses an in-memory token cache by default. In this case, we've extended the default cache to use a simple per-user session cache
AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectID));
// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
// The token will be stored in the ADAL token cache, for use in our controllers
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), credential, new string[] { clientId }, mostRecentPolicy);
}
// Used for avoiding yellow-screen-of-death
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
_log.Error("AuthenticationFailed!\r\nError={0}\r\nErrorDescription={1}\r\n{0}",
notification.ProtocolMessage.Error,
notification.ProtocolMessage.ErrorDescription,
notification.Exception.ToString());
notification.HandleResponse();
notification.Response.Redirect("/Home/OpenIdError?message=" + notification.ProtocolMessage.ErrorDescription);
return Task.FromResult(0);
}
}
External identities first need to 'sign up' as well before signing in. During sign up the external identity is linked to B2C.
In the sign up page you can ask additional attributes for your users, like a customer number. You need this for external identies and for the Local Account users in B2C, no difference between the two.
This is different behaviour compared to adding an identity provider without B2C, where every login just works.
Edit: Like Konstantin mentioned, the new combined sign-up or sign-in policy solves this problem:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-policies/#create-a-sign-up-or-sign-in-policy
I was running into the same issue, but was able to circumvent the user "Sign-Up" after user insertion. The issue turned out to be, that to have proper federation occur, the proper values need to be in place.
"identities": [
{
"signInType": "federated",
"issuer": "https://login.microsoftonline.com/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/v2.0",
"issuerAssignedId": "YYYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"
What was happening was that I was using "issuer": "myDomain.com" which was not resolving correctly to do a login; to which the user then had to "SignUp" via the federated IP.
By changing that from DNS readable name, to the MS login with my AD directories ID (the number provided when switching domain in Azure, XXXX-XXX ...) and the proper issuerAssignedId, from the originating AD issuer, it worked and the user was added.
I try to get OpenID Connect running... A user of my Web API managed to get an Authorization Code of a OpenID Connect Provider. How am I supposed to pass this code to my ASP.NET Web API? How do I have to configure OWIN Middleware such that I can get an Access Token using the Authorization Code?
UPDATE:
A SPA uses AJAX for communicating with my web service (ASP.NET Web API). In my web service a use OWIN Middleware. I set OpenIDConnect as the authentication mechanism. When the web service is called for the first time it successfully redirected the user to the login page of the OpenID Connect Provider. The user could login and got an Authorization Code as a result. AFAIK this code could now be used (by my web service) to the an Access Token. However, I don't know how to get this code back to my web service (is this done using a header?) and then what to configure to get the Access Token. I guess I could call the token endpoint manually but I would like to take advantage of the OWIN component instead.
BenV already answered the question, but there's more to consider.
class partial Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// ...
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
Notifications = new OpenIdConnectAuthenticationNotifications() {
AuthorizationCodeReceived = (context) => {
string authorizationCode = context.Code;
// (tricky) the authorizationCode is available here to use, but...
return Task.FromResult(0);
}
}
}
}
}
Two problems:
First of all, authorizationCode will get expired quickly. There's no sense in storing it.
The second problem is that AuthorizationCodeReceived event will not get fired for any of the page reloads as long as authorizationCode is not expired and stored inside the session.
What you need to do is to call AcquireTokenByAuthorizationCodeAsync which will cache it and handle properly inside TokenCache.DefaultShare:
AuthorizationCodeReceived = (context) => {
string authorizationCode = context.Code;
AuthenticationResult tokenResult = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, new Uri(redirectUri), credential);
return Task.FromResult(0);
}
Now, before every call to the resource, invoke AcquireTokenSilentAsync to get the accessToken (it will use TokenCache or silently use refreshToken ). If token is expired, it will raise AdalSilentTokenAcquisitionException exception (invoke access code renew procedure).
// currentUser for ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")
AuthenticationResult authResult = await context.AcquireTokenSilentAsync(resourceUri, credential, currentUser);
Calling AcquireTokenSilentAsync is very fast if token is cached.
Looks like the recommended approach is to use the AuthorizationCodeReceived event to exchange the Auth code for an Access Token. Vittorio has a blog entry that outlines the overall flow.
Here's an example from this sample app on GitHub of the Startup.Auth.cs code to set this up:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceID);
return Task.FromResult(0);
},
...
}
Note: The AuthorizationCodeReceived event is invoked only once when authorization really takes place. If the auth code is already generated and stored, this event is not invoked. You have to logout or clear cookies to force this event to take place.
This is now built into Microsoft.Owin 4.1.0 or later. You can use SaveTokens to make the id_token available and then RedeemCode to get an access token and make that available
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
ClientSecret = "redacted",
RedirectUri = postLogoutRedirectUri,
//This allows multitenant
//https://github.com/Azure-Samples/guidance-identity-management-for-multitenant-apps/blob/master/docs/03-authentication.md
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) =>
{
return Task.FromResult(0);
}
},
SaveTokens = true,
// Required for the authorization code flow to exchange for tokens automatically
// using this means you will need to provide RedirectUri and ClientSecret
RedeemCode = true
}
);
You can then access the tokens through the HttpContext object
var result = Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies").GetAwaiter().GetResult();
string idToken = result.Properties.Dictionary["id_token"];
string accessToken = result.Properties.Dictionary["access_token"];
Sources:
How to get access token from httpcontext using owin and Mvc 5
You need to bypass the default owin validation to do custom Authorization:
new OpenIdConnectAuthenticationOptions
{
...,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false
},
TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = ClaimTypes.Role },
This line of code solved my issue. We need to validate the issuer to be false.