Configure a cloudservice for autentication with Azure Active Directory - azure

I've got a single tenant cloudservice that I want to be accessible to my company's employees only. The solution has a web role and a worker role.
Web.Config
<add key="ida:Tenant" value="MyCompany.onmicrosoft.com" />
<add key="ida:Audience" value="https://MyCompany.onmicrosoft.com/MySolutionWebRole" />
<add key="ida:ClientID" value="44421xxx-xxxx-xxxx-xxxx-xxxxxxx7024" />
<add key="ida:Password" value="i6fMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx4Yk=" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44322/" />
Also, I got the same settings in Cloud.config:
<Setting name="ida.Tenant" value="MyCompany.onmicrosoft.com" />
<Setting name="ida.Audience" value="https://MyCompany.onmicrosoft.com/MySolutionWebRole" />
<Setting name="ida.ClientID" vvalue="44421xxx-xxxx-xxxx-xxxx-xxxxxxx7024" />
<Setting name="ida.Password" value="i6fMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx4Yk=" />
<Setting name="ida.AADInstance" value="https://login.microsoftonline.com/{0}" />
<Setting name="ida.PostLogoutRedirectUri" value="https://localhost:44322/" />
Moving on to Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
Finally, I've got the [Authorize] tag in my controller set up.
In the Azure Active Directory setup, I've got my cloudservice registered.
Application type is Web app / API, and Multi-tenanted is "No". Logout url is set to https://localhost:44322/Account/EndSession. I have not changed or edited the Manifest.
When I try to enter the cloud service, I'm redirected to my organization login page (all well so far), but after entering password I'm greeted my an error message.
We have problems loggin you in. We received an illegal request. (freely translated)
Correlation ID: 21f4089f-1952-4f57-aead-173a66c1408d Timestamp:
2016-09-26 10:24:14Z AADSTS90093: This application requires
application permissions to another application. Consent for
application permissions can only be performed by an administrator.
Sign out and sign in as an administrator or contact one of your
organization's administrators.
The url for the login request is as follows (the sceen where I enter my password);
https://login.microsoftonline.com/ fd2xxxxx-xxxx-xxxx-xxxxxxxf3f2/
oauth2/authorize?client_id=444xxxxx-xxxx-xxxx-xxxxxxxx024
&redirect_uri=https%3a%2f%2flocalhost%3a44322%2f
&response_mode=form_post &response_type=code+id_token
&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties
%3dYkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I have been looking at two example solutions based on web apps found at
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect and
https://github.com/Azure-Samples/active-directory-dotnet-webapp-multitenant-openidconnect
I'd be really grateful for any help on this matter

Turnes out I have to edit my manifest in Azure Active Directory App registration:
"requiredResourceAccess": [
{
"resourceAppId": "00000002-0000-0000-c000-000000000000",
"resourceAccess": [
{
"id": "311a71xxxx-xxxx-xxxx-xxxx7156d8e6",
"type": "Scope"
},
{
"id": "5778995axxxx-xxxx-xxx-xxxx63a9f3f4d04",
"type": "Role"
}
When I removed the last entry (role, probably the worker role), I got a screen prompting me if I wanted to grant the the application reading rights for my Azure AD profile. After answering OK i was forwarded to localhost:44322 with a 404. The solution to that was to remove the postLogoutRedirectUri key from the configuration files, as well as to remove the two lines in Startup.Auth.cs
//PostLogoutRedirectUri = postLogoutRedirectUri,
//RedirectUri = postLogoutRedirectUri,
Now it's working as intended :)

Related

How to Login User from AZURE AD in asp net core web api

I'm Developing an API which have single Sign-On Features (Google, Microsoft, Facebook).
I'm facing an issue to authenticate the user with Microsoft Azure AD.
I have configured Azure Portal and middleware.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(APIConfig.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(APIConfig.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
I Have a Login ActionMethod which have following code.
if API Parameter pass {loginby = 4} then i need to redirect to microsoft login page for authentication just like i did for google i don't want to put authorize attribute.
if (userView.LoginBy == (int)UserLoginBy.MicrosoftAzure)
{
????? what to place here to redirect to microsoft account for user login
}
if (model.LoginBy == (int)UserLoginBy.Google)
{
string[] Scopes = { GmailService.Scope.GmailReadonly};
string ApplicationName = Constant.ApplicationName;
UserCredential credential;
// string credPath = "credentials/gmail-dotnet-quickstart.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = Constant.ClientId,
ClientSecret = Constant.ClientSecret
},
Scopes,
model.Email,
CancellationToken.None).Result;
model.ExternalAccountToken = credential.Token.AccessToken;
model.ExternalAccountRefreshToken = credential.Token.RefreshToken;
model.Email = credential.UserId;
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
One of the workaround you can follow;
Before going to authenticate with AZURE AD make sure that you have Register an application with AZURE AD and provide the below in your appsettings.json file.
For example:-
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
//"Domain": "qualified.domain.name",
"TenantId": "72xxxxxxxxxxxxxxxxxxxxxxx",
"ClientId": "69xxxxxxxxxxxxxxxxxxxxxx",
"CallbackPath": "http://localhost:5204/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
Then We need to specify various scopes for our APIs if we are working with multiple projects or Microservices because the scope is necessary for authorizing the API, such as read and write access.
For that, choose the Azure _Auth application's Expose an API option. The popup to create the scopes will appear when you click the + Add Scope button.
For complete setup please refer the below links:-
MICROSOFT DOCUMENTATION|Enable authentication in your own web API by using Azure AD B2C
BLOG|Enable Azure AD Authentication Using .Net 5.0 Web API

Azure AD and Redirect Uri with infinite login loop

Good morning,
I created a Blazor Server Side application in .NET5 with the standard VS2019 template and I want to authenticate via Azure OpenId.
The app must be deployed under IIS in HTTP mode and a reverse proxy will give users an HTTPS url: the final url given by the reverse proxy is https://myapp-test.domain.it.
My problem is that both when I debug the application in VS both when I publish it under IIS the application reload in loops the authentication page and the the login fails.
My Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
});
string redirectUri = Configuration.GetSection("AzureAd:RedirectUri").Value;
string clientSecret = Configuration.GetSection("AzureAd:ClientSecret").Value;
if (!string.IsNullOrWhiteSpace(redirectUri))
{
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true;
var redirectToIdpHandler = options.Events.OnRedirectToIdentityProvider;
options.Events.OnRedirectToIdentityProvider = async context =>
{
await redirectToIdpHandler(context);
context.ProtocolMessage.RedirectUri = redirectUri;
};
});
}
//...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders();
//...
}
My appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "XXXXXXX",
"TenantId": "XXXXXXX",
"ClientId": "XXXXXXX",
"ClientSecret": "XXXXXXX",
"RedirectUri": "https://myapp-test.domain.it",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
In the redirect URIs on Azure I setted:
https://myapp-test.domain.it/
https://myapp-test.domain.it/signin-oidc
I run the application (or I hosted it under IIS) with the following url: http://localhost:39146; but as I said calling the app with http://localhost:39146 or with https://myapp-test.domain.it produces and "infinite" login loop that fails at the end.
Initially you can try with latest versions of Microsoft packages ,
which may fix the issue.
This problem may occur if website uses http protocol.Please check if the reverse proxy listen HTTPS request but forward the request to the app as HTTP.See forward-the-scheme-for-linux-and-non-iis-reverse-proxies.Note that the cookie is only sent for secure https request.
One way is to force https navigation to the site.
You can customize the Cookies Authentication middleware to allow the authentication AspNet cookie for both http and https scheme by setting the CookieSecure attribute to CookieSecureOption.Never as followed in the Startup.Auth.cs file but not recommended in certain cases.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieSecure = CookieSecureOption.Never
});
So some cases of owin middleware please try to update app’s Microsoft.Owin.Host.SystemWeb package be at least version 3.1.0.0
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
});
Also you can check this way OWIN and Azure AD HTTPS to HTTP Redirect Loop - Stack Overflow
References:
infinite redirect loop between Azure AD and MVC Asp.net app (aaddevsup.xyz)

How to resolve Invalid Audience when I trye to verify if a user exists in Azure Active Directory?

Reading the documentation of Microsoft Graph, I found an example to connect to the Azure Active Directory and verify if a previously registered user exists.
The problem is that the example throws this error when I try to do the request:
Graph service exception Error code: InvalidAuthenticationToken
Error message: Access token validation failure. Invalid audience.
My code is practically the same as the documentation shows how to do it. This is the code:
List<String> scopes = new ArrayList<String>();
String clientId = "XXXXXXX";
String clientSecret = "YYYYYYYY";
String tenantId = "ZZZZZZZZZ";
String permissions = "api://" + clientId + "/.default";
scopes.add(permissions);
final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId(clientId)
.clientSecret(clientSecret)
.tenantId(tenantId)
.build();
final TokenCredentialAuthProvider tokenCredentialAuthProvider =
new TokenCredentialAuthProvider(scopes, clientSecretCredential);
final GraphServiceClient graphClient =
GraphServiceClient
.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
User resultUser = null;
try {
UserCollectionPage ucp = graphClient.users().buildRequest().filter(
"startsWith(mail,'" + email + "')").get();
List<User> result = ucp.getCurrentPage();
User u = result.get(0);
return new ResponseEntity<>(resultUser, HttpStatus.OK);
}
catch (IndexOutOfBoundsException e) {}
The connection to the Azure Active Directory looks fine, because it shows SUCCESS after login connection with the credentials:
2021-12-16 21:38:10.994 INFO 28072 --- [onPool-worker-1]
c.azure.identity.ClientSecretCredential :
Azure Identity => getToken() result for scopes api://570f77fe-098f-42cd-8a22-a29fa1d9c7c0/.default: SUCCESS
Another thing I want to show you, is the decoded token, may it can helps to bring me a solution:
Token:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCIsImtpZCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCJ9.eyJhdWQiOiJhcGk6Ly81NzBmNzdmZS0wOThmLTQyY2QtOGEyMi1hMjlmYTFkOWM3YzAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8zOTdlZDAzMS0zOTM1LTQwYjAtOWM2OS0xNGZkMTE2NGRiOGYvIiwiaWF0IjoxNjM5NzA4Mzk5LCJuYmYiOjE2Mzk3MDgzOTksImV4cCI6MTYzOTcxMjI5OSwiYWlvIjoiRTJaZ1lOaTJjRGEveHRHMmZldTAxUTdxVHI1MUFnQT0iLCJhcHBpZCI6IjU3MGY3N2ZlLTA5OGYtNDJjZC04YTIyLWEyOWZhMWQ5YzdjMCIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzM5N2VkMDMxLTM5MzUtNDBiMC05YzY5LTE0ZmQxMTY0ZGI4Zi8iLCJvaWQiOiJiMmRlYTQ3NS1lODlhLTRiNjQtOGM5Mi0yMTg4MGM5ODhmMTYiLCJyaCI6IjAuQVNrQU1kQi1PVFU1c0VDY2FSVDlFV1Rial81M0QxZVBDYzFDaWlLaW42SFp4OEFwQUFBLiIsInN1YiI6ImIyZGVhNDc1LWU4OWEtNGI2NC04YzkyLTIxODgwYzk4OGYxNiIsInRpZCI6IjM5N2VkMDMxLTM5MzUtNDBiMC05YzY5LTE0ZmQxMTY0ZGI4ZiIsInV0aSI6IjNRQ1hJZGhMTVVLUnh3NkxwbndoQUEiLCJ2ZXIiOiIxLjAifQ.SU9kpXWs6fP-9T8QlPOJT8rKihPdtd38B8frOiS1I36T5LjewEyTmHgTEKWKgPhGxUHkmYWQxi6itNsn_4H_XUpgvVU2oNxoYsumQIW8rQZUx7hZeqxPrY3hbl_UfJgCtZ3J_0z6Ekk6QmBA-VBFEueq5lzjlARqYgTyQQ-uaNUtyrih4HyOkSkwcC8rs20UAjguunDVAzVucjweB0B2m9ib-uT1hhJlOihOwNtZ-A28QYNihp4r8HkriMaZMqutrdrVhH_--0OpF1O7lFEGEeDQeDozWi4SjboWJcODgsOGsZ7HxHd3Lx5mv8vJ0MvC8z_GIRWpuQqJuZ7eXQeFWg
Decoded token:
{
"typ": "JWT",
"alg": "RS256",
"x5t": "Mr5-AUibfBii7Nd1jBebaxboXW0",
"kid": "Mr5-AUibfBii7Nd1jBebaxboXW0"
}.{
"aud": "api://570f77fe-098f-42cd-8a22-a29fa1d9c7c0",
"iss": "https://sts.windows.net/397ed031-3935-40b0-9c69-14fd1164db8f/",
"iat": 1639708399,
"nbf": 1639708399,
"exp": 1639712299,
"aio": "E2ZgYNi2cDa/xtG2feu01Q7qTr51AgA=",
"appid": "570f77fe-098f-42cd-8a22-a29fa1d9c7c0",
"appidacr": "1",
"idp": "https://sts.windows.net/397ed031-3935-40b0-9c69-14fd1164db8f/",
"oid": "b2dea475-e89a-4b64-8c92-21880c988f16",
"rh": "0.ASkAMdB-OTU5sECcaRT9EWTbj_53D1ePCc1CiiKin6HZx8ApAAA.",
"sub": "b2dea475-e89a-4b64-8c92-21880c988f16",
"tid": "397ed031-3935-40b0-9c69-14fd1164db8f",
"uti": "3QCXIdhLMUKRxw6LpnwhAA",
"ver": "1.0"
}.[Signature]
I get this token with this URL:
https://graph.microsoft.com/v1.0/
Using the following code:
url = new URL(urlHost);
token = tokenCredentialAuthProvider.getAuthorizationTokenAsync(url).get();
Work around on the error InvalidAuthenticationToken
Error message: Access token validation failure. Invalid audience
aud (audience) : this Identifies the intended recipient of the token - its audience.
Your API must validate this value and reject the token if the value doesn't match.
Based on your given details you are using version v1.0
In v1.0 tokens it can be the client ID or the resource URI used in the request, depending on how the client requested the token
To resolve this error, you need to make sure the audience in the token is https://graph.microsoft.com by using scope: https://graph.microsoft.com/.default during your token acquisition call
make sure below permissions are consented under the application whose client ID you are using during token acquisition call.
1)User.ReadWrite.All
2)Directory.ReadWrite.All
To provide consent, you need to navigate to:
1) Azure Portal > Azure Active Directory > App Registration > search the application using client ID > API Permissions > Add Permission
2) Click on the ADD Permission

"JWT Validation Failed: JWT not present.." in Azure API Management Service

For reference I am attempting to reproduce the solution talked about here: https://www.tech-findings.com/2020/02/securing-logic-app-with-azure-active-directory.html to use API Management to secure an Azure Logic App.
I am getting a JWT Error. When I visit the app url in the browser it gives:
{ "statusCode": 404, "message": "Resource not found" }
In the API Management Service test I get:
HTTP/1.1 401 Unauthorized
Following the trace through it shows:
validate-jwt (-0.111 ms)
{
"message": "JWT Validation Failed: JWT not present.."
}
I did some googling and tried the solutions at:
JWT validation failure error in azure apim
and
https://learn.microsoft.com/en-us/answers/questions/108008/azure-apim-jwt-token-validation-policy.html
Here is the inbound policy of from the API Management design:
<policies>
<inbound>
<base />
<set-method id="apim-generated-policy">POST</set-method>
<rewrite-uri id="apim-generated-policy" template="/request/paths/invoke//?api-version=2016-06-01&sp=/triggers/request/run&sv=1.0&sig={{[[LOGIC APP NAME]]_request-invoke_XXXXXXXXXXXXXXXXXXXXXXXX}}" />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Request is not authorized or token failed" require-expiration-time="false" require-scheme="Bearer" require-signed-tokens="true">
<openid-config url="https://login.windows.net/[[TENANT NAME]].onmicrosoft.com/.well-known/openid-configuration" />
<audiences>
<audience>[[THE ID OF A REGISTERED APP]]</audience>
</audiences>
</validate-jwt>
<set-header name="Authorization" exists-action="delete" />
<set-header name="apim-generated-policy" exists-action="delete" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
This is the manifest of the registered app:
{
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"acceptMappedClaims": null,
"accessTokenAcceptedVersion": 2,
"addIns": [],
"allowPublicClient": null,
"appId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"appRoles": [],
"oauth2AllowUrlPathMatching": false,
"createdDateTime": "2020-12-22T19:48:36Z",
"disabledByMicrosoftStatus": null,
"groupMembershipClaims": null,
"identifierUris": [
"api://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
],
"informationalUrls": {
"termsOfService": null,
"support": null,
"privacy": null,
"marketing": null
},
"keyCredentials": [],
"knownClientApplications": [],
"logoUrl": null,
"logoutUrl": null,
"name": "LabsTestApp",
"oauth2AllowIdTokenImplicitFlow": false,
"oauth2AllowImplicitFlow": false,
"oauth2Permissions": [],
"oauth2RequirePostResponse": false,
"optionalClaims": null,
"orgRestrictions": [],
"parentalControlSettings": {
"countriesBlockedForMinors": [],
"legalAgeGroupRule": "Allow"
},
"passwordCredentials": [],
"preAuthorizedApplications": [],
"publisherDomain": "[[TENANT NAME]].onmicrosoft.com",
"replyUrlsWithType": [],
"requiredResourceAccess": [],
"samlMetadataUrl": null,
"signInUrl": null,
"signInAudience": "AzureADandPersonalMicrosoftAccount",
"tags": [],
"tokenEncryptionKeyId": null
}
Hoping you can help out - point me in the right direction.
For this question, there are more than one problem in your steps.
1. You mentioned the error { "statusCode": 404, "message": "Resource not found" } when you request the url in browser. The reason is when you request it in browser, it request with Get method but the url should be request with Post method. So it shows 404 not found.
2. When you test in API Management service, it shows 401 Unauthorized. The reason for this error is you did not provide the access token or the access token you provided is invalid. The steps in the document you mentioned are incomplete, please refer to the steps below:
1). First please make sure you have completed all of the steps in the document you provided.
2). Then go to the app you registered in azure ad and click "Manifest" tab, add a appRole in the json of "Manifest".
You can specify a name(anything you want) for this role, I named the role as Writer as the screenshot above shows. And you can also specify a "id"(in GUID format) as the value of the id field in appRole. For more details of add appRole, you can refer to this document.
3). You need to register another app in azure ad as the client app. Do same register operation as your document shows to register the other app, I registered the app and named huryGetToken4. Go to this app and click "API permissions" tab, click "Add a permission" and find the original app you registered, then add the permission Writer.
After add the Writer permission, you also need to click "Grant admin consent for xxx".
Then click "Certificates & secrets" tab, click "New client secret" to generate a client secret. Copy this secret because it will just show one time.
4). Then you need to get access token, please refer to the screenshot below to request for access token.
In the screenshot above, you need to replace the <tenant id> with your tenant id in the host url. And you also need to input the first three parameters. The last parameter grant_type is static.
5). Request for the access token, you will get the response like below screenshot.
Copy the value of access_token and paste it to this page to decode the token, you can see the claim roles with Writer permission in it. This claim is what you need to check in the <validate-jwt> policy in your APIM.
6). Go to your apim and click the pencil icon of validate-jwt policy.
7). Edit the "Reauired claims" like screenshot below:
8). After that, you can test the api in APIM service. Add a header with key: Authorization, value: Bearer <your access token>(note there is a blank between Bearer and access token).

AspCore 2.2 Azure Active Directory : Authorization failed

I try to integrate Azure Active Directory and Asp.net CORE 2.2.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
Appsettings.json
{"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxxx.onmicrosoft.com",
"TenantId": "xxxxxx",
"ClientId": "xxxx" } },"AllowedHosts": "*"}
The results:
Error : info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
Please, i found any solution for this issue.
Thank you very much
May be a good solution is to modify the startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
sharedOptions.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
})
.AddAzureAD(options => Configuration.Bind("AzureAD", options));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
And includes in the controller
[Authorize(AuthenticationSchemes = "AzureAD")]
[Route("api/[controller]")]
[ApiController]
AddAzureADBearer adds JWT Bearer authentication to your app for Azure Active Directory Applications. It is usually used by protecting your application with AAD tokens . If that is you scenario , check the detailed error message of Authorization failed. You can refer to below link for code samples :
https://stackoverflow.com/a/57619013/5751404
Another scenario is you want to add Azure AD login authentication .The simplest way is to use the default Azure AD template : Change Authentication --> Work or School Accounts . Or manually add the Microsoft.AspNetCore.Authentication.AzureAD.UI package and use AddAzureAD extension:
https://stackoverflow.com/a/54546245/5751404

Resources