Protect ASP.NET API with IdentityServer & Bearer - asp.net

I have a 3 tier application, where I have:
A blazor web application
a HTTP API
An Identity Server
Currently, I have 2 kinds of controllers on the HTTP API:
general-purpose API: can be accessed without authentication, but only if the call comes from the Web Application
personal purpose API: can be accessed only after authentication
Right now, the "personal purpose API" working fine. this API is only accessible when the user is logged in.
But, I also need to protect the "general-purpose API" from any hacker, right now a call to "post/list" returns an "unauthorized error"!
I wish to protect this API, without authentication, but it must be only accessible from my web application.
Do you know how can I do this? Is there something wrong or missing in my code?
Here is the controller code on the HTTP API side :
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class PostsController : ControllerBase
{
[HttpGet]
[Route("post/list")]
public async Task<List<Item>> GetListAsync()
{
...
}
}
Here is my code on the HTTP API side :
context.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = true;
options.ApiName = "SoCloze";
});
And here is my code on the Web Application side:
context.Services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(ApplicationConstants.LoginCookieExpirationDelay);
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = true;
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.ClientId = configuration["AuthServer:ClientId"];
options.ClientSecret = configuration["AuthServer:ClientSecret"];
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("role");
options.Scope.Add("email");
options.Scope.Add("phone");
options.Scope.Add("SoCloze");
options.ClaimActions.MapAbpClaimTypes();
});

You should make your controller anonymous. With your configuration simply remove your Authorize attribute from your controller. If you had applied a global policy you'd need to add the anonymous attribute to your controller:
[AllowAnonymous]
I'm not sure what you want to achieve, but I guess you want cross-site protection. That is, you want to limit certain endpoints from being accessed only from the origin of your blazor app.
You need to trust in the client browser for Same Origin Policy. The same origin policy controls interactions between two different origins. Cross-origin writes are typically allowed, Cross-origin embedding is typically allowed and Cross-origin reads are typically disallowed, but read access is often leaked by embedding.
This protection is only for XHR calls from your browser and it doesn't protect againts direct access (postman, fiddler, any http client...).
To prevent cross-origin writes in your posts you can use Antiforgery tokens. Asp Net Core create this tokens automatically if you specify POST in your forms:
<form asp-controller="Todo" asp-action="Create" method="post">
...
</form>
Or
#using (Html.BeginForm("Create", "Todo"))
{
...
}
This will reject any post from any form that has not been previously loaded from your server.

To keep the API simple, you of course want to only accept tokens from the trusted IdentityServer.
So basically you need a generic access token that is secure, but not tied to any human user. You could have the web app to request an access token using the client credentials flow and then use that token all the time when you want to access the API as a non-authenticated user.
In IdentityServer you would setup a separate client just for this.
Also using the IdentityModel library could help you out here (as a Worker Applications) https://identitymodel.readthedocs.io/en/latest/aspnetcore/worker.html
see also https://docs.duendesoftware.com/identityserver/v5/tokens/requesting/
This picture shows what I mean:

Related

Auth setup of B2C Web API accessing confidential client (multitenant) Web API

I have a multi-tenant Web API of tenant A. It has permissions exposed and accepted by a B2C Web API of tenant B. (The API App Services live in the same tenant, but their AD instances are separate due to the one being a B2C tenant).
I have the following code in my B2C Web API authenticating with tenant B to access the multi-tenant Web API of tenant A.
I'm using Microsoft.Identity.Web (v1.25.5) and .NET Core (6), and so I don't have to handle making unnecessary calls to get an access token, I'm using the IDownstreamWebApi helper classes (though I have tried without according to the documentation, but land up with the same error.)
My code:
appsettings.json
program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
},
options => {
builder.Configuration.Bind("AzureAdB2C", options);
})
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
})
.AddDownstreamWebApi("TenantAApi", options =>
{
builder.Configuration.Bind("TenantAApi", options);
})
.AddInMemoryTokenCaches();
Calling code:
var response = await _downstreamWebApi.CallWebApiForAppAsync(
"TenantAApi",
options =>
{
options.HttpMethod = httpMethod;
options.RelativePath = url;
}, content);
var responseContent = await response.Content.ReadAsStringAsync();
The error I receive:
MSAL.NetCore.4.48.0.0.MsalClientException:
ErrorCode: tenant_override_non_aad
Microsoft.Identity.Client.MsalClientException: WithTenantId can only be used when an AAD authority is specified at the application level.
at Microsoft.Identity.Client.AbstractAcquireTokenParameterBuilder`1.WithTenantId(String tenantId)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForAppAsync(String scope, String authenticationScheme, String tenant, TokenAcquisitionOptions tokenAcquisitionOptions)
at Microsoft.Identity.Web.DownstreamWebApi.CallWebApiForAppAsync(String serviceName, String authenticationScheme, Action`1 downstreamWebApiOptionsOverride, StringContent content)
What doesn't make sense is that I'm calling this from a B2C Web API, from what I can see in the existing AbstractAcquireTokenParameterBuilder code (see line 292), B2C authorities are not AAD specific, and even so, adding an Authority or AadAuthorityAudience to my AzureAdB2C config object has no effect.
Am I missing a configuration property somewhere?
It seems that this isn't possible according to the following wiki post -
https://github.com/AzureAD/microsoft-identity-web/wiki/b2c-limitations#azure-ad-b2c-protected-web-apis-cannot-call-downstream-apis
For now I'm going to try a different approach and get an access token with a ConfidentialClientApplication object, and if that doesn't work, create a separate app registration in the other tenant and authenticate with that instead.

.Net Core 6 Can't get Claims after authenticated by ADFS

I recently got a problem about authenticated by ADFS
In dot net core 6, below is my scenario.
I got one Web-Api site host on IIS in server 2019, and an ADFS server
Web -Api domain like https://xxx.domain.com
ADFS one like https://ooo.domain.com
I use WS-federation in my program
both browsers can't get value, edge and chrome
setting is
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
}).AddWsFederation(options =>
{ options.MetadataAddress = "my adfs url/FederationMetadata/2007-06/FederationMetadata.xml";
options.Wreply = "https://my webpai url/checkstate";
options.CallbackPath = "/checkstate";
options.BackchannelTimeout = TimeSpan.FromMinutes(1);
options.RemoteAuthenticationTimeout = TimeSpan.FromMinutes(15);
})
.AddCookie();
web-api
signin action for auth and will redirect to adfs server login page
and auth back to the checkstate action this part are work very well.
But I can't Get the value what I want.
In my understanding use the ws-federation(Microsoft.AspNetCore.Authentication.WsFederation6.0.3)
don't need to fetch other service for parse the value.
whole workflow should like this
Users fetch the Api => auth => adfs login => success and get adfs shared value in cookies
=> back to the callback action => get value in action and do something.
When I opened the Dev tools, I can see the real flow like
Signin 302 =>adfs 200 this with a lot cookies
prefix and key is "MSISAUTH"
=> checkstate 200 but, no cookies
I already contact with the ADFS server cruise member and got response said
"We done every setting and it's look fine. "
My question is Did I miss some key-part ?
and is any misunderstanding on workflow?
[Authorize]
[HttpGet("signin")]
public IActionResult Signin()
{
return new EmptyResult();
}
[HttpPost("checkstate")]
public IActionResult CheckState()
{
var name = User.Claims.FirstOrDefault(x=>x.Type == ClaimTypes.Name)?.Value;
return Ok($"Name:{name}");
}
My question is Did I miss some key-part ?
and is any misunderstanding on workflow?
How can I get the Claims value ?

.NET Core Identity - How generate token from another place than path/connect/token

in my web api application I get the acess token from http:applicationpath/connect/token with some parameters (this endpoint is from Identity I think, since we dont create it neither can see it).
But now I need to generate the token from a specific controller but cant see how to do this.
Someone knows how this can be made? Or even if it's possible?
Thanks
Some more info:
My application is an integrator (is this the word?) between an android app(app1) and other web application(app2).
1- The app1 user will send the login and password to my application .
2- Then my application will send then to the app2 who will, if everything goes well, return the app2 token .
3- Then I have to save this token in my db.
4- Then verify if the user exists in my db, and if not, save it.
5- And finally generate an token for my application and return it to the user.
Based on your comment:
But can I, instead of change de default endpoint, make another
endpoint that do the same (generate the token)?
it seems that you are rather looking for Extending discovery. This is quite easy actually.
Add a custom entry in the configuration of startup:
services.AddIdentityServer(options =>
{
options.Discovery.CustomEntries.Add("custom_token", "~/customtoken");
});
And add a controller that handles the request:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// In case a token is required for login, like the UserInfo endpoint:
//[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ApiController]
public class CustomTokenController : ControllerBase
{
[Route("customtoken")]
public IActionResult CustomTokenEndpoint()
{
return Ok();
}
}
Update
You can 'replace' the endpoint by disabling the default authorization endpoint and adding a custom endpoint as described above.
Disable the endpoint:
services
.AddIdentityServer(options =>
{
options.Endpoints.EnableAuthorizeEndpoint = false;
})
You may want to use the Authorize path constant.
public const string Authorize = ConnectPathPrefix + "/authorize";
Add the new endpoint:
services.AddIdentityServer(options =>
{
options.Discovery.CustomEntries.Add("authorization_endpoint", $"~/{Authorize}");
});
Please note, I didn't test it, but I think this should work.

Changing .Net Core OpenID Connect Authorization Flow 'redirect_uri' value

I've configured a .Net Core Web app to use OpenID Connect for authentication using the Authorization Code model as per my IdP sample instructions (https://www.onelogin.com/blog/how-to-use-openid-connect-authentication-with-dotnet-core):
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o => {
o.ClientId = "[Client ID]";
o.ClientSecret = "[Client Secret]";
o.Authority = "[Authority]";
o.ResponseType = "code";
o.GetClaimsFromUserInfoEndpoint = true;
});
Then my controller is set up to require authentication:
[Authorize]
public IActionResult About()
{
ViewData["Message"] = "You must be authenticated to view the About page";
return View();
}
I also have configured ngrok to provide a temporary public URL which should be used in the authentication flow redirect back to my site using:
ngrok http 5000 -host-header="localhost:5000"
This command successfully sets up the proxy and once running, I can browse to the site via the proxy url (e.g. https://75c97570.ngrok.io).
The issue I'm running into is that when I attempt to browse to the 'About' page I'm redirected to the IdP site and prompted to log-in as expected, however, the 'redirect_uri' value passed via the query string is my 'localhost' address (https://localhost:5000/signin-oidc) not the ngrok proxy address (https://75c97570.ngrok.io/signin-oidc). This is causing an issue because my IdP requires a non-local url (hence the ngrok proxy), so the redirect_uri value being passed (localhost) doesn't match the one configured in my IdP account (ngrok) and I receive an error message that the 'redirect_uri did not match any client's registered redirect_uris'.
I'm assuming this is a .Net configuration issue. Is there a way to tell .Net to use the ngrok proxy address for the 'redirect_uri' value on redirect as opposed to the localhost address? I've tried using the 'CallbackPath' option on the OpenID Connect configuration options, however it appears that this only allows for a sub-path of the current url (e.g. http://localhost:5000/[something]) and can't be used to specify a completely different url. Is there another way to configure the redirection to use the proxy url?
Thanks!
Ok, after some digging I found one solution to this issue. I added the following code to the initialization of my OpenIdConnect service:
.AddOpenIdConnect(o => {
...(snip)...
o.Events.OnRedirectToIdentityProvider = (context) =>
{
context.ProtocolMessage.RedirectUri = "https://75c97570.ngrok.io/signin-oidc";
return Task.FromResult(0);
};
...(snip)...
}
This does the trick of changing the 'redirect_uri' value which is passed to my IdP on the redirect. Not sure if this is the best way to handle this, however it does work.

Can IIS require SSL client certificates without mapping them to a windows user?

I want to be able to map SSL client certificates to ASP.NET Identity users. I would like IIS to do as much of the work as possible (negotiating the client certificate and perhaps validating that it is signed by a trusted CA), but I don't want IIS to map the certificate to a Windows user. The client certificate is passed through to ASP.NET, where it is inspected and mapped to an ASP.NET Identity user, which is turned into a ClaimsPrincipal.
So far, the only way I have been able to get IIS to pass the client certificate through to ASP.NET is to enable iisClientCertificateMappingAuthentication and set up a many-to-one mapping to a Windows account (which is then never used for anything else.) Is there any way to get IIS to negotiate and pass the certificate through without this configuration step?
You do not have to use the iisClientCertificateMappingAuthentication. The client certificate is accessible in the HttpContext.
var clientCert = HttpContext.Request.ClientCertificate;
Either you enable RequireClientCertificate on the complete site or use a separate login-with-clientcertificate page.
Below is one way of doing this in ASP.NET MVC. Hopefully you can use parts of it to fit your exact situation.
First make sure you are allowed to set the SslFlags in web.config by turning on feature delegation.
Make site accept (but not require) Client Certificates
Set path to login-with-clientcertificate-page where client certificates will be required. In this case a User controller with a CertificateSignin action.
Create a login controller (pseudo-code)
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[AllowAnonymous()]
public ActionResult CertificateSignIn()
{
//Get certificate
var clientCert = HttpContext.Request.ClientCertificate;
//Validate certificate
if (!clientCert.IsPresent || !clientCert.IsValid)
{
ViewBag.LoginFailedMessage = "The client certificate was not present or did not pass validation";
return View("Index");
}
//Call your "custom" ClientCertificate --> User mapping method.
string userId;
bool myCertificateMappingParsingResult = Helper.MyCertificateMapping(clientCert, out userId);
if (!myCertificateMappingParsingResult)
{
ViewBag.LoginFailedMessage = "Your client certificate did not map correctly";
}
else
{
//Use custom Membersip provider. Password is not needed!
if (Membership.ValidateUser(userId, null))
{
//Create authentication ticket
FormsAuthentication.SetAuthCookie(userId, false);
Response.Redirect("~/");
}
else
{
ViewBag.LoginFailedMessage = "Login failed!";
}
}
return View("Index");
}

Resources