Hello, I recently upgraded my abp version from 7.3.2 to 7.4.0, I don't know if this is related with upgrade, maybe this wasn't working fine before.
In angular part of the gdpr module, when i look at the source code, it checks the cookie consent, if it is true it doesn't show the accept cookie bar as I understand.
here is the code for checking the cookie, here cookie key is '.AspNet.Consent'
protected checkCookieConsent() {
const hasCookieConsent =
decodeURIComponent(this.document.cookie)
.split(' ')
.indexOf(this.cookieKey + '=true') > -1;
if (hasCookieConsent) {
this.showCookieConsent = false;
}
}
When i look at my cookies on chrome,I can see that it is true.
when i debug this, i can see that array from the code decodeURIComponent(this.document.cookie.split(' ') has an item like
here you can see indexOf shouldn't be .indexOf(this.cookieKey + '=true') but it should be .indexOf(this.cookieKey + '=true;') to make it work (';' semicolon at the end). I use chrome by the way. Maybe it works with other browsers, i didn't test it with others. Is there any trick that I can do to fix it fast?
Hello I recently upgraded to Abp v7.4.0, I am using file management module with abp, I customize it according to my needs and it was working fine. Now i have a problem with file download. I think there is a bug related with it. Since i customize it i couldn't be sure but I didn't override download part before, so it is likely from the new version.
Anyway here is the problem. For download to work first angular is doing a backend call to get a token. Then doing get request by using javascript window.open here is the file management module angular code.
downloadFile(file: FileInfo) {
return this.fileDescriptorService.getDownloadToken(file.id).pipe(
tap((res) => {
window.open(
`${this.apiUrl}/api/file-management/file-descriptor/download/${file.id}?token=${res.token}`,
'_self'
);
})
);
}
"this.fileDescriptorService.getDownloadToken" call is an authenticated but file-descriptor/download call is anonymous call.
On the backend side, when IDistributedCache is used it sets the token for the current tenant. so it normalizes the cache key. here is the code for it.
public virtual async Task<DownloadTokenResultDto> GetDownloadTokenAsync(Guid id)
{
var token = Guid.NewGuid().ToString();
await DownloadTokenCache.SetAsync(
token,
new FileDownloadTokenCacheItem { FileDescriptorId = id },
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
});
return new DownloadTokenResultDto
{
Token = token
};
}
here the current tenant id is set. So the problem is when you do the second call to /api/file-management/file-descriptor/download/ endpoint with window.open since it is anonymous and token is not set it doesn't get the current tenant id. here is the code for it.
[AllowAnonymous]
public virtual async Task<IRemoteStreamContent> DownloadAsync(Guid id, string token)
{
var downloadToken = await DownloadTokenCache.GetAsync(token);
if (downloadToken == null || downloadToken.FileDescriptorId != id)
{
throw new AbpAuthorizationException("Invalid download token: " + token);
}
FileDescriptor fileDescriptor;
using (DataFilter.Disable<IMultiTenant>())
{
fileDescriptor = await FileDescriptorRepository.GetAsync(id);
}
var stream = await BlobContainer.GetAsync(id.ToString());
return new RemoteStreamContent(stream, fileDescriptor?.Name);
}
here you get authorization exception since cache key is not normalized over here. even if i override and change the current tenant id to null, it gets the token but this time BlobContainer can not find the file since this file belongs to tenant. What i came up with is to send tenantId from user interface as a query string and override FileDescriptorController like this.
also i override the angular part and inject the new service as a download service. sth like
@Injectable()
export class CreativeDownloadService {
apiName = 'FileManagement';
get apiUrl() {
return this.environment.getApiUrl(this.apiName);
}
constructor(
private restService: RestService,
private fileDescriptorService: FileDescriptorService,
private environment: EnvironmentService,
private configStateService: ConfigStateService
) {}
downloadFile(file: FileInfo) {
const currentUser = this.configStateService.getOne("currentUser");
return this.fileDescriptorService.getDownloadToken(file.id).pipe(
tap((res) => {
window.open(
`${this.apiUrl}/api/file-management/file-descriptor/download/${file.id}?token=${res.token}&__tenant=${currentUser?.tenantId}`,
'_self'
);
})
);
}
}
I don't know how this was working before. I wonder if new version changed sth, by the way i use redis cache. Also sth I didn't understand is according to docs
giving query string __tenant should set CurrentTenant but it doesn't do so. Is this related with [AllowAnonymous] attribute? Thanks for the help and waiting for your reply.
Thank you for the help.
Hello, I didn't understand how i can pass the authorization header while i am redirecting the user from angular. Is there any sample code how to do that? I would be happy if you can share it. I fixed the problem by implementing another authentication schema, so in that way i can challenge the user to authenticate and when it is done i can sign in the user and redirect the user to the page. sth like this.
context.Services.AddAuthentication(options =>
{
options.DefaultScheme = "DoohlinkCustomPolicy";
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddPolicyScheme("DoohlinkCustomPolicy", "DoohlinkCustomPolicy", options =>
{
options.ForwardDefaultSelector = context =>
{
string authorization = context.Request.Headers[HeaderNames.Authorization];
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer "))
return JwtBearerDefaults.AuthenticationScheme;
else
return CookieAuthenticationDefaults.AuthenticationScheme;
};
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.Audience = "Doohlink";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(365);
})
.AddAbpOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.ResponseType = OpenIdConnectResponseType.Code;
options.ClientId = configuration["AuthServer:WebClientId"];
options.ClientSecret = configuration["AuthServer:WebClientSecret"];
options.UsePkce = true;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("roles");
options.Scope.Add("email");
options.Scope.Add("phone");
options.Scope.Add("Doohlink");
options.Events.OnTicketReceived = async (TicketReceivedContext e) =>
{
await e.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
e.Principal,
new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddDays(1)
});
};
});
and challenging the user to login in a controller.
public ActionResult Login()
{
return Challenge(new AuthenticationProperties { RedirectUri = "/hangfire" }, OpenIdConnectDefaults.AuthenticationScheme);
}
this works for now. But I would happy to know how to do it from angular. Because as i know when you do redirect from client side like. window.open() you can not pass authorization header. Or maybe I am wrong?
Hello again, Thanks for the explanation, can i ask how can i do the same for hangfire dashboard? If i write a mvc controller action, how can i redirect the user to auth server log in page and then redirect to hangfire dashboard?
Hello, I am trying to implement hangfire to my project. I managed to do that, the only problem that i have is with hangfire dashboard. If i do not use authentication for my hangfire dashboard it works fine. And i can access it. But when i have enabled the filter, i can not access the page. In HttpContext i can not see the user claims, so it return unauthenticated inside AbpHangfireAuthorizationFilter.
I logged in with admin rights and when i call a method from swagger endpoint i can see that claims are there for user and CurrentUser.IsAuthenticated property returns true. I couldn't understand why current user is unauthenticated (or claims are not in the context) when AbpHangfireAuthorizationFilter is triggered. any tips about it?
here is the onApplicationInitialization
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAbpRequestLocalization();
app.UseStaticFiles();
app.UseAbpSecurityHeaders();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
if (MultiTenancyConsts.IsEnabled)
{
app.UseMultiTenancy();
}
app.UseAuthorization();
app.UseSwagger();
app.UseAbpSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Doohlink API");
var configuration = context.GetConfiguration();
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
});
app.UseAuditing();
app.UseAbpSerilogEnrichers();
app.UseUnitOfWork();
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
AsyncAuthorization = new[] { new DoohlinkAuthorizationFilter() }
});
app.UseConfiguredEndpoints();
}
ps: to see the httpcontext I have changed AbpHangfireAuthorizationFilter to custom class inside my project here is DoohlinkAuthorizationFilter
public class DoohlinkAuthorizationFilter : IDashboardAsyncAuthorizationFilter
{
private readonly bool _enableTenant;
private readonly string _requiredPermissionName;
public DoohlinkAuthorizationFilter(bool enableTenant = false, string requiredPermissionName = null)
{
_enableTenant = requiredPermissionName.IsNullOrWhiteSpace() ? enableTenant : true;
_requiredPermissionName = requiredPermissionName;
}
public async Task<bool> AuthorizeAsync(DashboardContext context)
{
if (!IsLoggedIn(context, _enableTenant))
{
return false;
}
if (_requiredPermissionName.IsNullOrEmpty())
{
return true;
}
return await IsPermissionGrantedAsync(context, _requiredPermissionName);
}
private static bool IsLoggedIn(DashboardContext context, bool enableTenant)
{
var currentUser = context.GetHttpContext().RequestServices.GetRequiredService<ICurrentUser>();
if (!enableTenant)
{
return currentUser.IsAuthenticated && !currentUser.TenantId.HasValue;
}
return currentUser.IsAuthenticated;
}
private static async Task<bool> IsPermissionGrantedAsync(DashboardContext context, string requiredPermissionName)
{
var permissionChecker = context.GetHttpContext().RequestServices.GetRequiredService<IPermissionChecker>();
return await permissionChecker.IsGrantedAsync(requiredPermissionName);
}
}
and this is httpcontext quickwatch
Thanks a lot, i have seen the fix now, I am closing the issue then.
Hello @liangshiwei. As you mention it works when you await, probably when i try to await i did sth wrong. It was late at night :) Thank you for sharing the issue link with me So it seems, collection has been updated from two threads. And collection that is updated in Volo.Abp.Uow.UnitOfWorkExtensions.GetOrAddItem is not thread safe. Maybe changing that to ConcurrentDictionary can help. https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=net-5.0
Thank you @mahmut.
Hello again, you can find the project in this github repo. https://github.com/cangunaydin/abpConcurrencyIssue to produce the same error you have to do the followings.
1- Clone the project.
2- Go to aspnet-core\etc\docker
3- execute run-docker-sideapps.ps1 this will create the redis and postgres(postgis) container.(stick to these images since appsettings has been configured according to those docker images and geolocation is involved)
4- Build project and run dbmigrator. This will seed a new tenant named "Tribulus" and one screen belongs to this tenant with id: "ad16f9e2-bf39-43cf-af69-47b7388ee9cd". You can check TenantDataSeeder class if you want.
5- abp install-libs inside AuthServer folder then Run Doohlink.AuthServer and Doohlink.HttpApi.Host project
6- Run angular app and get bearer token for Tribulus tenant with username: admin, password: 123qwe, note the bearer token and tenantid to somewhere, you will use them on step 8 7- Install Jmeter to do multiple http requests async. If you want you can use another tool but important part is you need bunch of async calls at the same time. https://jmeter.apache.org/download_jmeter.cgi Download zip file, unzip it then run jmeter.bat
8- After running the Jmeter, you need to open the TestJmeter.jmx file on the root folder of the project. This is a script that will do the call to the endpoint.
9- Change the bearer token and tenantid to what you got from step 6. You need to do that from Http Header Manager
10-Run the jmeter, it is gonna take 10 seconds, you can see if http requests are successful on treeview. Most of them will succeed around 5 of them will fail. you can look at the logs afterwards.