Problem in refreshing the login token from client to identity server - microservices

I have setup an Identity Server 4 on a .Net 6 web app. My web UI is another web app that is configured as the client of the Identity Sever. User is correctly refered to the login page when request accessing to a secured page/api and login is done OK. The solution also has other microservices that are also configured to use IS as oidc. The problem is after a while if I do not refresh the page, authentication fails when calling webapis. When I check the request, before the main call to the webapi controller, a request to the IS is made but is refused with CORS exception. I have configured the IS web app to accept CORS like this:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
and then:
app.UseCors("CorsPolicy");
What I am missing?
The mentioned settings did not solve the problem

The problem is might be caused from the expiration of the cookie or token (I'm not sure). But you should also add
builder.Services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowedOrigins = { /*webUIOriginHere!NotUrl!*/ }
};
});
to the program.cs of Identity Server webapp and the problem should be solved.
Also adding AnyOrigin is dangerous. try doing something like this:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins( webUIOrigin )
.AllowAnyMethod()
.AllowAnyHeader());
});

Related

Spring Keycloak Adapter sometimes returns with "Token is not active" when uploading files

lately we are facing an issue that our Spring Boot backend service (stateless REST service) SOMETIMES returns an HTTP 401 (Unauthorized) error when users try to upload files >70 MB (or in other words, when the request takes longer than just a couple of seconds). This does not occur consistently and only happens sometimes (~every second or third attempt).
The www-authenticate header contains the following in these cases:
Bearer realm="test", error "invalid_token", error_description="Token is not active"
Our Spring (Boot) configuration is simple:
keycloak.auth-server-url=${KEYCLOAK_URL:http://keycloak:8080/auth}
keycloak.realm=${KEYCLOAK_REALM:test}
keycloak.resource=${KEYCLOAK_CLIENT:test}
keycloak.cors=true
keycloak.bearer-only=true
Essentially, our frontend code uses keycloak-js and does the following to keep the access token fresh:
setInterval(() => {
// updates the token if it expires within the next 5s
this.keycloak.updateToken(5).then((refreshed) => {
console.log('Access token updated:', refreshed)
if (refreshed) {
store.commit(AuthMutationTypes.SET_TOKEN, this.keycloak.token);
}
}).catch(() => {
console.log('Failed to refresh token');
});
}, 300);
Further, we use Axios and a respective request filter to inject the current token:
axios.interceptors.request.use(
(request: AxiosRequestConfig) => {
if (store.getters.isAuthenticated) {
request.headers.Authorization = 'Bearer ' + store.getters.token;
}
return request;
}
);
This worked very well so far and we have never experienced such a thing for our usual GETs/POSTs/PUTs etc. This happens only when users try to upload files larger than (around) 70MBish.
Any hint or tip how to debug this any further? We appreciate any help...
Cheers

How should I set net core api cors?

I am coding an unofficial twitter api for myself. Then I send a get to this api using the console screen in my browser with the following method.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
such
httpGet(https://localhost:44311/WeatherForecast/alienationxs/true);
the problem is that when i do this via www.google.com it's ok and json data reaches me. but when I do it via twitter.com I get the following error.
via google.com
my cors settings on api
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
options.AddDefaultPolicy(builder =>
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); ;
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "twitterAPI", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "twitterAPI v1"));
}
app.UseRouting();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
all i want is to reach my api via twitter.com just like google.com.
First, let's separate the flies from the cutlets.
Cross-Origin Resource Sharing (CORS) - is a separate security layer.
Content Security Policy (CSP) - is a separate security layer, it's appied before CORS. After passing through CSP yous can face with CORS if last one is breached.
As you can see from error message "... because it violates the following Content Security Policy directive ...", you faced with CSP violation therefore your CORS settings have no mean.
What's goin on.
You enter twitter.com web page and tries to execute connect request to localhost:44311 on behalf of twitter web page. But twitter's web page protected by CSP which forbid such requests:
Pay attention on 'connect-src' directive, which governs XMLHttpRequest().
The www.google.com web page does not have CSP, therefore you request on behalf of google does success.
The Twitter API does not support CORS.

Getting access_token from identityserver returns null

I have 3 projects, an MVC .net core website, an API service and an IdentityServer (IdentityServer4). Logging in to the website works like a charm. It's when I want to get data from the API the problems are starting. Getting the access_token from the httpcontext fails and returns null. The strange thing is that when I debug this, I seem to be getting an access_token back from the httpcontext. Only when I run the website from the live webserver it causes problems.
I configured my OpenIdConnect as follows:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultAuthenticateScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "https://idserverurl";
options.RequireHttpsMetadata = true;
options.ClientId = "clientid";
options.ClientSecret = "xxxxxxxx";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
};
});
To set the bearertoken for the API calls I use de following code:
var client = new HttpClient();
var accessToken = await HttpContext.GetTokenAsync("access_token");
client.SetBearerToken(accessToken);
When I run this code in debug I get the access_token from the HttpContext. When I run this from the live servers, I get null.
Does anybody have any idea what I'm doing wrong? Could it be a configuration mistake at server level?
I think I solved it myself.
It had to do with the line
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
By removing this line and altering the lines of code where I get my claims (they have a different key now), I am getting the access_token.
FYI I published the project to my own IIS. That way I could attach Visual Studio to the dotnet process and debug it.
Why it worked locally and not online I still don't know.
The above code looks OK - ultimately the tokens should come back from the Authorization Server after user login, then be persisted between requests in the authentication cookie.
Are you able to run Fiddler on your live web server and capture a trace of traffic, including that between your Web App and the Authorization Server? That's the ideal way to troubleshoot - and see if the expected tokens / cookies are present in the HTTPS requests.
In case you're not aware, in .Net Core 2.0 you can construct your web app's HttpClient with an HttpClientHandler that sets proxy details like this:
public class ProxyHttpHandler : HttpClientHandler
{
public ProxyHttpHandler()
{
this.Proxy = new WebProxy("http://127.0.0.1:8888");
}
}
In older versions of MS OpenIdConnect libraries I've seen problems related to load balancing, where not all servers could decrypt the authentication cookie. So if your live servers are load balanced the details in this older link may be relevant.

SignalR and OpenId Connect

I have a server which uses ASP.NET Core Web Api and OpenIddict as authorization framework. Now I've added an SignalR host and want to add authorisation to it.
From different sources I found that SignalR (JS Client) wants that you send the access token in the querystring or by cookie as websockets don't support headers.
As the authentication middleware doesn't check the querystring or cookie container for an authorization entry I need to implement such an provider/retriever/resolver which reads this value by myself.
I've found a solution for IdentityServer but nothing about OpenIddict.
Where/How do I implement such an token resolver with OpenIddict?
If you use JwtBearerAuthentication then you can use OnMessageReceived to set token:
Events = new JwtBearerEvents()
{
OnMessageReceived = async (ctx) =>
{
ctx.Token = ctx.Request.Query["<qs-name>"];
}
}
Or if you use IdentityServerAuthentication then you can use TokenRetriever(not tested but it should be something like this):
TokenRetriever = (ctx) =>
{
return ctx.Request.Query["<qs-name>"];
}
Just like #adem-caglin mentioned, in IdentityserverAuthentication you use TokenRetriever and can go with the built-in functions if what you're after is the standard bearer header or a query string
TokenRetriever = (request) =>
{
// by default calls TokenRetrieval.FromAuthorizationHeader()(request);
// check if request is to signalr endpoint and only then apply FromQueryString
return TokenRetrieval.FromQueryString()(request);
}

Request with token from ADAL for Cordova returns 401 response from Web Api

I'm hoping someone can help with this:
I have a web api secured with Azure AD Bearer Authentication, where I have two web clients that can successfully authenticate on the web api using bearer tokens from AD. The Web API and both web applications are configured as applications in AD. I've tried to use ADAL for Cordova for accessing the web api a iOS/Android app but it's returning 401.
ClaimsPrincipal.Current.Identity.IsAuthenticated is returning false.
I'm using the client id for the native application I've setup in Azure AD, and I'm receiving the token but this token is invalid. After I've parsed the token on jwt.io, everything seems correct but I've noticed the token doesn't have a header.
I've added permissions to access the Web Api and sign in and access AD as the user.
The code I'm using in Cordova is below, the authority I'm using is the same as the other apps that are working. Where resource is the app Id for the Web Api in AD, and client id is the client id for the native app in Azure Ad.
// Attempt to authorize user silently
AuthenticationContext.acquireTokenSilentAsync(resource, clientId)
.then(function (result) {
sessionService.logIn(result.idToken);
console.log(result);
deferred.resolve();
}, function () {
// We require user credentials so triggers authentication dialog
AuthenticationContext.acquireTokenAsync(resource, clientId, redirectUri)
.then(function (result) {
console.log(result);
sessionService.logIn(result.idToken);
deferred.resolve();
}, function (err) {
console.log("Failed to authenticate" + err);
deferred.reject("failed to authenticate");
});
});
I've also tried using result.accessCode, which also doesn't work.
StartUp.Auth.cs in Web Api:-
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudiences = Audiences
}
});
}
Can anyone help please?
Thanks
You appear to be sending the wrong token to the API - you are supposed to send result.accessToken. See https://github.com/Azure-Samples/active-directory-cordova-multitarget/blob/master/DirSearchClient/js/index.js for an example.

Resources