microsoft / microsoft/typespec
[Java]: Easier support for modifying scopes
- Dominant language
- Java
- Stars
- 5.9k
- Forks
- 394
- Avg merge
- 1d 23h
- Merged PRs (30d)
- 104
Description
### Clear and concise description of the problem
Java generates the following
```
@useAuth(
ApiKeyAuth | OAuth2Auth<[
{
type: OAuth2FlowType.implicit,
authorizationUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
scopes: ["https://search.azure.com/.default"],
}
]>
)
```
with `scopes` being a `private static final String[]` with the scope value in the definition as the only value. For example:
```java
@Generated
private static final String[] DEFAULT_SCOPES = new String[] { "https://search.azure.com/.default" };
```
and later when creating a client
```java
if (tokenCredential != null) {
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES));
}
```
For services that require sovereign cloud audience scope support this means writing complicated post-code generation customizations.
Instead, to simplify this, Java could continue to generate `DEFAULT_SCOPES` but add in a `private String[] scopes` that defaults to `DEFAULT_SCOPES` that can be mutated but does expose a method to do so. And if a service needs sovereign cloud support it could add a non-`@Generated` method that will be retained if `partial-update` is enabled. For example,
```java
@Generated
private static final String[] DEFAULT_SCOPES = new String[] { "https://search.azure.com/.default" };
@Generated
private String[] scopes = DEFAULT_SCOPES;
```
and in client creation
```java
if (tokenCredential != null) {
String[] scopeToUse = (scopes == null) ? DEFAULT_SCOPES : scopes;
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, scopes));
}
```
and if a service needs to add sovereign cloud support it could be as easy as
```java
/**
* Sets the Audience to use for authentication with Microsoft Entra ID.
*
* The audience is not considered when using a {@link #credential(AzureKeyCredential) shared key}.
*
* If {@code audience} is null the public cloud audience will be assumed.
*
* @param audience The Audience to use for authentication with Microsoft Entra ID.
* @return The updated SearchClientBuilder object.
*/
public SearchClientBuilder audience(SearchAudience audience) {
if (audience == null) {
this.scopes = DEFAULT_SCOPES;
} else {
this.scopes = new String[] { audience.toString() }; // the string from SearchAudience is the appropriate value for the cloud target
}
return this;
}
```
### Checklist
- [x] Follow our [Code of Conduct](https://github.com/microsoft/typespec/blob/main/CODE_OF_CONDUCT.md)
- [x] Read the [docs](https://typespec.io/docs/).
- [x] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
Contributor guide
Assessment
This issue has not been assessed yet.