microsoft / microsoft/aspire

[Aspire.Hosting.SqlServer] Allow specifying a user in the connection string

Open
#7,655 6 comments 0 reactions 0 assignees View on GitHub
area-integrations sqlserver
Dominant language
C#
Stars
6.3k
Forks
991
Avg merge
2d 15h
Merged PRs (30d)
196

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

Currently, the user ID for the connection string is hard-coded as `sa`, it would be useful if we could pass a user instead. For me, it would be useful because I can run tests as my production user, instead of `sa`.

https://github.com/dotnet/aspire/blob/acdf5012407c2ab0259f4b6f075acb6c668949f3/src/Aspire.Hosting.SqlServer/SqlServerServerResource.cs#L36-L38

### Describe the solution you'd like

Allow passing the user ID as a parameter, either in the `SqlServerServerResource` or the `SqlServerDatabaseResource`. As a workaround, I created a resource with parent, but I had to copy the connection string code:

```csharp
public class DatabaseUser(
string name,
SqlServerDatabaseResource parent,
string userName,
IResourceBuilder password) : Resource(name), IResourceWithParent, IResourceWithConnectionString
{
public SqlServerDatabaseResource Parent { get; } = parent;

private ReferenceExpression ConnectionString =>
ReferenceExpression.Create(
$"Server={Parent.Parent.PrimaryEndpoint.Property(EndpointProperty.IPV4Host)},{Parent.Parent.PrimaryEndpoint.Property(EndpointProperty.Port)};User ID={userName};Password={password.Resource};TrustServerCertificate=true;Database={Parent.DatabaseName};");

///
/// Gets the connection string expression for the SQL Server.
///
public ReferenceExpression ConnectionStringExpression
{
get
{
if (this.TryGetLastAnnotation(out var connectionStringAnnotation))
{
return connectionStringAnnotation.Resource.ConnectionStringExpression;
}

return ConnectionString;
}
}

public ValueTask GetConnectionStringAsync(CancellationToken cancellationToken = default)
{
if (this.TryGetLastAnnotation(out var connectionStringAnnotation))
{
return connectionStringAnnotation.Resource.GetConnectionStringAsync(cancellationToken);
}

return ConnectionString.GetValueAsync(cancellationToken);
}
}
```

### Additional context

This is useful for end-to-end tests where you want the environment to be as close to production as possible, so using the `sa` user can make you miss GRANT issues.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.