Giter Club home page Giter Club logo

artifacts-credprovider's Introduction

Azure Artifacts Credential Provider

The Azure Artifacts Credential Provider automates the acquisition of credentials needed to restore NuGet packages as part of your .NET development workflow. It integrates with MSBuild, dotnet, and NuGet(.exe) and works on Windows, Mac, and Linux. Any time you want to use packages from an Azure Artifacts feed, the Credential Provider will automatically acquire and securely store a token on behalf of the NuGet client you're using.

Build Status

Prerequisites

MSBuild on Windows

Install Visual Studio version 15.9-preview1 or later to get the required version of MSBuild (15.8.166.59604 or later). Alternatively, you can download MSBuild directly by downloading the Build Tools for Visual Studio. MSBuild is also installed as a part of the .NET Core SDK.

NuGet

NuGet(.exe) on the command line version 4.8.0.5385 or later is required. The recommended NuGet version is 5.5.x or later as it has some important bug fixes related to cancellations and timeouts.

dotnet

The default installation requires dotnet SDK version 6.0.x.

While the NuGet credential provider requires the dotnet runtime, the pip artifacts-keyring requires the dotnet SDK.

Setup

If you are using dotnet or nuget, you can use the Azure Artifact Credential Provider by adding it to NuGet's plugin search path. This section contains both manual and scripted instructions for doing so.

Dotnet needs the netcore version to be installed. NuGet and MSBuild need the netfx version to be installed.

Installation on Windows

Automatic PowerShell script

PowerShell helper script

  • To install netcore, run installcredprovider.ps1
    • e.g. iex "& { $(irm https://aka.ms/install-artifacts-credprovider.ps1) }"
  • To install both netfx and netcore, run installcredprovider.ps1 -AddNetfx. The netfx version is needed for nuget.exe.
    • e.g. iex "& { $(irm https://aka.ms/install-artifacts-credprovider.ps1) } -AddNetfx"

Manual installation on Windows

  1. Download the latest release of Microsoft.NuGet.CredentialProvider.zip
  2. Unzip the file
  3. Copy the netcore (and netfx for nuget.exe) directory from the extracted archive to $env:UserProfile\.nuget\plugins (%UserProfile%/.nuget/plugins/)

Using the above is recommended, but as per NuGet's plugin discovery rules, alternatively you can install the credential provider to a location you prefer, and then set the environment variable NUGET_PLUGIN_PATHS to the .exe of the credential provider found in plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe. For example, $env:NUGET_PLUGIN_PATHS="my-alternative-location\CredentialProvider.Microsoft.exe". Note that if you are using both nuget and dotnet, this environment variable is not recommended due to this issue: NuGet/Home#8151

Installation on Linux and Mac

Automatic bash script

Linux or Mac helper script

Examples:

  • wget -qO- https://aka.ms/install-artifacts-credprovider.sh | bash
  • sh -c "$(curl -fsSL https://aka.ms/install-artifacts-credprovider.sh)"

Note: this script only installs the netcore version of the plugin. If you need to have it working with mono msbuild, you will need to download the version with both netcore and netfx binaries following the steps in Manual installation on Linux and Mac

Manual installation on Linux and Mac

  1. Download the latest release of Microsoft.NuGet.CredentialProvider.tar.gz
  2. Untar the file
  3. Copy the netcore (and 'netfx' for msbuild /t:restore command) directory from the extracted archive to $HOME/.nuget/plugins

Using the above is recommended, but as per NuGet's plugin discovery rules, alternatively you can install the credential provider to a location you prefer, and then set the environment variable NUGET_PLUGIN_PATHS to the .dll of the credential provider found in plugins\netcore\CredentialProvider.Microsoft\CredentialProvider.Microsoft.dll. For example, $env:NUGET_PLUGIN_PATHS="my-alternative-location\CredentialProvider.Microsoft.dll".

Users requiring .NET 6, such as ARM64 users, can manually download the .NET 6 version Microsoft.Net6.NuGet.CredentialProvider of the 1.0.0 release.

Automatic usage

  • MSBuild in Visual Studio Developer Command Prompt with Visual Studio 15.9+
  • Azure DevOps Pipelines NuGetAuthenticate task
  • Azure DevOps Pipelines NuGet task, NuGetCommandV2 version 2.145.3+ (Azure DevOps Server 2019 Update 1+)

Use

Because the Credential Provider is a NuGet plugin, it is most commonly used indirectly, by performing a NuGet operation that requires authentication using dotnet, nuget, or msbuild.

dotnet

The first time you perform an operation that requires authentication using dotnet, you must either use the --interactive flag to allow dotnet to prompt you for credentials, or provide them via an environment variable.

If you're running interactively navigate to your project directory and run:

dotnet restore --interactive

Once you've successfully acquired a token, you can run authenticated commands without the --interactive flag for the lifespan of the token which is saved in the session token cache location.

nuget

The nuget client will prompt for authentication when you run a restore and it does not find credential in the session token cache location. By default, it will attempt to open a dialog for authentication and will fall back to console input if that fails.

nuget restore

When using Windows and you are already signed in to Azure DevOps, Windows Integrated Authentication may be used to get automatically authenticated as the signed in user.

msbuild

The first time you perform an operation that requires authentication using msbuild, you must use the /p:nugetInteractive=true switch to allow msbuild to prompt you for credentials. For example, to restore packages, navigate to your project or solution directory and run:

msbuild /t:restore /p:nugetInteractive=true

Once you've successfully acquired a token, you can run authenticated commands without the /p:nugetInteractive=true switch.

Unattended build agents

Azure DevOps Pipelines

Use the NuGet Authenticate task before running NuGet, dotnet or MSBuild commands that need authentication.

Other automated build scenarios

If you're running the command as part of an automated build on an unattended build agent outside of Azure DevOps Pipelines, you can supply an access token directly using the VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable. The use of Personal Access Tokens is recommended. You may need to restart the agent service or the computer before the environment variables are available to the agent.

Docker containers

Managing NuGet credentials in Docker scenarios

Azure DevOps Server

The Azure Artifacts Credential Provider may not be necessary for an on-premises Azure DevOps Server on Windows. If the credential provider is needed, it cannot acquire credentials interactively, therefore, the VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable must be used as an alternative. Supply a Personal Access Token directly using the VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable.

From Azure DevOps Server 2020 RC1 forward, the NuGet Authenticate task can be used in Pipelines.

Session Token Cache Locations

The Credential Provider will save session tokens in the following locations:

  • Windows: $env:UserProfile\AppData\Local\MicrosoftCredentialProvider
  • Linux/MAC: $HOME/.local/share/MicrosoftCredentialProvider/

Environment Variables

The Credential Provider accepts a set of environment variables. Not all of them we recommend using in production, but these two are considered safe.

  • NUGET_CREDENTIALPROVIDER_SESSIONTOKENCACHE_ENABLED: Controls whether or not the session token is saved to disk. If false, the Credential Provider will prompt for auth every time.
  • VSS_NUGET_EXTERNAL_FEED_ENDPOINTS: Json that contains an array of service endpoints, usernames and access tokens to authenticate endpoints in nuget.config. Example:
 {"endpointCredentials": [{"endpoint":"http://example.index.json", "username":"optional", "password":"accesstoken"}]}

Release version 1.0.0

Release version 1.0.0 was released in March 2022. Netcore version 1.0.0 of the Artifacts Credential Provider requires .NET Core 3.1. Older versions than 1.0.0 required .NET Core 2.1. Microsoft.NetCore2.NuGet.CredentialProvider asset is no longer available. Use Microsoft.NetCore3.NuGet.CredentialProvider.zip instead.

1.0.0 release also publishes the credential provider for .NET 6 users as Microsoft.Net6.NuGet.CredentialProvider.

Help

The windows plugin, delivered in the netfx folder of Microsoft.NuGet.CredentialProvider.zip, ships a stand-alone executable that will acquire credentials. This program will place the credentials in the same location that the .dll would if it were called by nuget.exe, dotnet.exe, or msbuild.exe. The stand-alone executable will also print the available command options, environment variables, and credential storage locations. This information is reproduced here:

C:\> .\CredentialProvider.Microsoft.exe -h
Command-line v1.0.6: .\CredentialProvider.Microsoft.exe -h

The Azure Artifacts credential provider can be used to acquire credentials for Azure Artifacts.

Note: The Azure Artifacts Credential Provider is mainly intended for use via integrations with development tools such as .NET Core and nuget.exe.
While it can be used via this CLI in "stand-alone mode", please pay special attention to certain options such as -IsRetry below.
Failing to do so may result in obtaining invalid credentials.

Usage - CredentialProvider.Microsoft -options

GlobalOption          Description
Plugin (-P)           Used by nuget to run the credential helper in plugin mode
Uri (-U)              The package source URI for which credentials will be filled
NonInteractive (-N)   If present and true, providers will not issue interactive prompts
IsRetry (-I)          If false / unset, INVALID CREDENTIALS MAY BE RETURNED. The caller is required to validate returned credentials themselves, and if
                      invalid, should call the credential provider again with -IsRetry set. If true, the credential provider will obtain new credentials
                      instead of returning potentially invalid credentials from the cache.
Verbosity (-V)        Display this amount of detail in the output [Default='Information']
                      Debug
                      Verbose
                      Information
                      Minimal
                      Warning
                      Error
RedactPassword (-R)   Prevents writing the password to standard output (for troubleshooting purposes)
Help (-?, -h)         Prints this help message
CanShowDialog (-C)    If true, user can be prompted with credentials through UI, if false, device flow must be used [Default='True']
OutputFormat (-F)     In standalone mode, format the results for human readability or as JSON. If JSON is selected, then logging (which may include Device
                      Code instructions) will be logged to standard error instead of standard output.
                      HumanReadable
                      Json

List of Environment Variables
    The following is a list of environment variables that can be used to modify the
    behavior of the credential provider. They may be used for workarounds but their
    use is not supported. Use at your own risk.

Log Path
    NUGET_CREDENTIALPROVIDER_LOG_PATH
        Absolute path to a log file where the provider will write log messages.

Session Token Cache Enabled
    NUGET_CREDENTIALPROVIDER_SESSIONTOKENCACHE_ENABLED
        Boolean to enable/disable the Session Token cache.

Supported Hosts
    NUGET_CREDENTIALPROVIDER_VSTS_HOSTS
        Semi-colon separated list of hosts that the credential provider supports.

Session Token Time Validity
    NUGET_CREDENTIALPROVIDER_VSTS_SESSIONTIMEMINUTES
        Time in minutes the generated Session Tokens will be valid for.
        The default for Personal Access Tokens is 90 days.
        The default for JWT (self-describing) tokens is 4 hours.
        The maximum allowed validity period for JWT tokens is 24 hours.

Token Type
    NUGET_CREDENTIALPROVIDER_VSTS_TOKENTYPE
        Specify 'Compact' to generate a Personal Access Token, which may
        have a long validity period as it can easily be revoked from the UI,
        and sends a notification mail on creation.
        Specify 'SelfDescribing' to generate a shorter-lived JWT token,
        which does not appear in any UI or notifications
        and is more difficult to revoke.
        By default PATs are generated rather than JWTs,
        unless authentication can be performed non-interactively.

Build Provider URI Prefixes
    VSS_NUGET_URI_PREFIXES
        Semi-colon separated list of hosts the build provider supports.

Build Provider Access Token
    VSS_NUGET_ACCESSTOKEN
        The Personal Access Token that will be returned as credentials by
        the build provider.

Build Provider Service Endpoint Json
    VSS_NUGET_EXTERNAL_FEED_ENDPOINTS
        Json that contains an array of service endpoints, usernames and
        access tokens to authenticate endpoints in nuget.config.
        Example: {"endpointCredentials": [{"endpoint":"http://example.index.json",
        "username":"optional", "password":"accesstoken"}]}

Cache Location
    The Credential Provider uses the following paths to cache credentials. If
    deleted, the credential provider will re-create them but any credentials
    will need to be provided again.

    MSAL Token Cache
    C:\Users\someuser\AppData\Local\.IdentityService

    Session Token Cache
    C:\Users\someuser\AppData\Local\MicrosoftCredentialProvider\SessionTokenCache.dat

Windows Integrated Authentication
    NUGET_CREDENTIALPROVIDER_WINDOWSINTEGRATEDAUTHENTICATION_ENABLED
        Boolean to enable/disable using silent Windows Integrated Authentication
        to authenticate as the logged-in user. Enabled by default.

Device Flow Authentication Timeout
    NUGET_CREDENTIALPROVIDER_VSTS_DEVICEFLOWTIMEOUTSECONDS
        Device Flow authentication timeout in seconds. Default is 90 seconds.

NuGet workarounds
    NUGET_CREDENTIALPROVIDER_FORCE_CANSHOWDIALOG_TO
        Set to "true" or "false" to override any other sources of the
        CanShowDialog parameter.

MSAL Authority
    NUGET_CREDENTIALPROVIDER_MSAL_AUTHORITY
        Set to override the authority used when fetching an MSAL token.
        e.g. https://login.microsoftonline.com/organizations

MSAL Token File Cache Enabled
    NUGET_CREDENTIALPROVIDER_MSAL_FILECACHE_ENABLED
        Boolean to enable/disable the MSAL token cache. Enabled by default.

Provide MSAL Cache Location
    NUGET_CREDENTIALPROVIDER_MSAL_FILECACHE_LOCATION
    Provide the location where the MSAL cache should be read and written to.

Troubleshooting

How do I know the cred provider is installed correctly? / I'm still getting username/password prompt after installing

This means that either nuget/dotnet was unable to find the cred provider from NuGet's plugin search path, or the cred provider failed to authenticate so the client defaulted to the username/password prompt. Verify the cred provider is correctly installed by checking it exists in the nuget/plugins folder in your user profile (Refer to the setup docs). If using nuget.exe and used the install script to install the cred provider, please make sure you ran it with -AddNetfx.

How do I get better error logs from the cred provider?

Run the nuget.exe/dotnet command with detailed verbosity to see more cred provider logs that may help debugging (nuget.exe -verbosity detailed, dotnet --verbosity detailed).

How do I find out if my issue is a real 401?

Run the credential provider directly with the following command: C:\Users\<user>\.nuget\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe -I -V Verbose -U "https://pkgs.dev.azure.com/{organization}/{project-if-feed-is-project-scoped}/_packaging/{feed}/nuget/v3/index.json". Check you have the right permissions from the feed permissions.

In an Azure DevOps Pipeline, verify you have set the right permissions for the pipeline by following the docs.

Cred provider used to work but now it asks me to update to .NET 6.0 or .NET Core 3.1.

Because .NET Core 2 is out of support, you should update to .NET Core 3.1 or greater to keep using the latest versions of the credential provider.

.NET Core 3.1 will also be removed from future versions. See the announcement here.

If you keep using the unsupported .NET Core 2.1 you must use Artifacts Credential Provider version 0.1.28 or lower.

Contribute

This project welcomes contributions and suggestions; see CONTRIBUTING for more information. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

When submitting a pull request, please include a description of the problem your PR is trying to solve, details about the changes, and how the change was tested.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

artifacts-credprovider's People

Contributors

aldoms avatar alexvtor avatar amp-powell avatar apluche avatar aude avatar bladedeyna avatar cheesebaron avatar crmann1 avatar dependabot[bot] avatar edgarrs avatar embetten avatar jcrpaquin avatar jiaw37 avatar jmyersmsft avatar johnschmeichel avatar johnterickson avatar jotaylo avatar keithrob avatar ksigmund avatar luber avatar magleaso avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar nayanshah avatar phil-hodgson avatar satbai avatar shadargee1982 avatar shubham90 avatar viktorhofer avatar zarenner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

artifacts-credprovider's Issues

Auth does not work with msbuild /restore if VSS_NUGET_EXTERNAL_FEED_ENDPOINTS has a secret

If VSS_NUGET_EXTERNAL_FEED_ENDPOINTS is set as an environment variable like:

{"endpointCredentials": [{"endpoint":"https://accountname.pkgs.visualstudio.com/_packaging/feed-name/nuget/v3/index.json", "username":"username", "password":"$(VstsToken)"}]}

where $(VstsToken) is a secret variable (which it would be , of course), then the credential provider does not work as it does not have access to the variable.

Unable to log-out of credential provider

When running CredentialProvider for the first time, it will pop up a Microsoft log-in window (presumably via the "Trying authentication provider Browser-based federated authentication..." option. When using my correct Azure DevOps account with Artifacts option enabled, all works well.

Somehow, I had to supply my login id/password again in that microsoft login window, but I mistakenly used the wrong account (which does not have Artifacts option). I now continuously get 402 error from Nuget (Payment Required: user does not have license). This is all correct up to this point.

My issue now, is how do I revoke that credential / log-in and reset CredentialProvider to ask me for login username/password again? If I run Visual Studio under a different name as such: "runas
/netonly /user:anotherUserName devenv.exe", it will then ask me to re-log in via Microsoft pop up window once CredentialProvider is run.

Any way to work around this via options?

credprovider and VSS_NUGET_EXTERNAL_FEED_ENDPOINTS with Docker

Hello,

Maybe you could help me with authentication with private NuGet feed, I already spend a day for different solutions and notice this repo, but I'm still struggling to make it done.

I'm using below Dockerfile with different variations, but I'm getting Unauthorized each time

FROM microsoft/dotnet:2.2-sdk AS build
ARG VSS_NUGET_EXTERNAL_FEED_ENDPOINTS
WORKDIR /api

#ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS={"endpointCredentials":[{"endpoint":"https://name.pkgs.visualstudio.com/_packaging/Feed/nuget/v3/index.json","username":"PAT","password":"PAT"}]}


# Auth with private feed
RUN wget https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh \
   && chmod +x installcredprovider.sh \
   && ./installcredprovider.sh


# Copy csproj and restore as distinct layers
COPY ["App.csproj", "./"]
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS runtime
WORKDIR /api
COPY --from=build /api/out ./
EXPOSE 4444
ENTRYPOINT ["dotnet", "App.dll"]

I tried with ARGs and ENVs to set the VSS_NUGET_EXTERNAL_FEED_ENDPOINTS, but each time I'm getting this error:

error NU1101: Unable to find package Package.Name. No packages exist with this id in source(s): nuget.org

Currently we don't have dedicated NuGet.Config in the project, maybe it's the case of this issue?
That I need to create it and add this private repo to it?

Thank you.

Setup artifacts-credprovider in TFS CI/CD with Docker

Hello,

I'm trying to restore Nuget packages from a private TFS in a docker container using TFS CI/CD. Unfortunately I'm still getting 401 Unauthorized.

Docker File

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY ["Web/Web.csproj", "Web/"]
RUN curl -s -L https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash
COPY nuget.config ./
RUN export VSS_NUGET_EXTERNAL_FEED_ENDPOINTS={"endpointCredentials": [{"endpoint":"http://[redacted]/tfs/SDCC/_packaging/SDCC/nuget/v3/index.json", "username":"[user]", "password":"[PAT]"}]}
ARG token
ENV SYSTEM_ACCESSTOKEN = $token
ENV DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0
RUN dotnet restore "Web/Web.csproj" --configfile nuget.config -nowarn:msb3202,nu1503 --verbosity diag
COPY . .
WORKDIR "/src/Web"
RUN dotnet build "Web.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "Web.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "Web.dll"]

Nuget.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
    <add key="SDCC" value="https://[Redacted]/tfs/SDCC/_packaging/SDCC/nuget/v3/index.json" />
 </packageSources>
 <packageSourceCredentials>
    <SDCC>
        <add key="Username" value="[UserName]" />
        <add key="ClearTextPassword" value="[PAT]" />
    </SDCC>    
</packageSourceCredentials>
</configuration>

If I install CredProvider I receive that it can't find the nuget package.

If I don't use CredProvider and don't use nuget.config I receive a message, but I guess that's because I don't have included the nuget.config in the docker image

error NU1101: Unable to find package Sdcc.Core. No packages exist with this id in source(s): nuget.org

As response, Either I receive unauhtorized

 Response status code does not indicate success: 401 (Unauthorized)

Invaldi status code was supplied

 GSSAPI operation failed with error - An invalid status code was supplied (Configuration file does not specify default realm). [/src/Web/Web.csproj]

I'm lost, I have no other idea what to do, as a workaround which works, but breaks the principle of Docker is that In my CI/CD TFS Pipeline, I'm making the restore / build / publish and push everything in Docker container and push the Docker Image.

Thanks

How to set CanShowDialog from MSBuild?

Hi @satbai I'm using the credprovider from MSBuild, and even though I pass /p:NugetInteractive=true the CanShowDialog is still set to false:

IsNonInteractive: False, CanShowDialog: False

It looks like there is no way to thread through the setting to the task from MSBuild?

Can't restore with NuGet.exe (error running the CredentialProvider)

Hi,

I am trying to use the CredentialProvider to authenticate with a feed in Azure Artifacts, but I can't get it to work with nuget.exe restore.

I have the CredentialProvider in a custom folder and set the NUGET_CREDENTIALPROVIDERS_PATH env var to that same place.

However, when I attemp to run NuGet restore, it keeps failing with 401 (Unauthorized).

I tried to pass the switch -verbosity detailed to nuget.exe, and I get the followin stack trace:

Restoring NuGet package Node.js.x86.0.10.36. WARNING: The credential plugin model used by 'C:\svn\trunkrepo\ServiceStudio\..\Commons\ThirdParty\AzureCredentialsProvider\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe' is deprecated. Please contact the provider of the plugin for an alternative. More information about the recommended plugin model can be found at 'https://aka.ms/nuget-cross-platform-authentication-plugin'. CredentialProvider.Microsoft: Unhandled Exception: PowerArgs.ValidationArgException: detailed is not a valid value for type LogLevel, options are Debug, Verbose, Information, Minimal, Warning, Error CredentialProvider.Microsoft: at PowerArgs.ArgRevivers.ReviveEnum(Type t, String value, Boolean ignoreCase) CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.Revive(String commandLineValue) CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.Populate(HookContext context) CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.PopulateArguments(List1 arguments, HookContext context)
CredentialProvider.Microsoft: at PowerArgs.Args.ParseInternal(CommandLineArgumentsDefinition definition, String[] input)
CredentialProvider.Microsoft: at PowerArgs.Args.<>c__DisplayClass13_0.b__0()
CredentialProvider.Microsoft: at PowerArgs.Args.Execute[T](Func1 argsProcessingCode) CredentialProvider.Microsoft: at PowerArgs.Args.ParseAction(CommandLineArgumentsDefinition definition, String[] args) CredentialProvider.Microsoft: at PowerArgs.Args.ParseAction(Type t, String[] args) CredentialProvider.Microsoft: at PowerArgs.Args.Parse(Type t, String[] args) CredentialProvider.Microsoft: at PowerArgs.Args.Parse[T](String[] args) CredentialProvider.Microsoft: at PowerArgs.Args.<>c__DisplayClass22_01.b__0()
CredentialProvider.Microsoft: at System.Threading.Tasks.Task1.InnerInvoke() CredentialProvider.Microsoft: at System.Threading.Tasks.Task.Execute() CredentialProvider.Microsoft: --- End of stack trace from previous location where exception was thrown --- CredentialProvider.Microsoft: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() CredentialProvider.Microsoft: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) CredentialProvider.Microsoft: at NuGetCredentialProvider.Program.<Main>d__11.MoveNext() in E:\A\_work\857\s\CredentialProvider.Microsoft\Program.cs:line 63 CredentialProvider.Microsoft: --- End of stack trace from previous location where exception was thrown --- CredentialProvider.Microsoft: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() CredentialProvider.Microsoft: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) CredentialProvider.Microsoft: at NuGetCredentialProvider.Program.<Main>(String[] args)

Can I get some help to understand what's going on? It looks like when I build using MSBuild (without calling nuget.exe directly) it works, but I can't get it to work with nuget.exe.

Best Regards,
Diogo Oliveira

dotnet list package --outdated returns 401

On my Mac development machine, everything is working for commands like dotnet restore or dotnet add package {private package}.

However checking outdated items with dotnet list package --outdated I get the following error:

Ginsberg-2:TS.XXXX.Api user$ dotnet list package --outdated

The following sources were used:
   https://api.nuget.org/v3/index.json
   https://XXXX.pkgs.visualstudio.com/_packaging/XXXX/nuget/v3/index.json

error: Unable to load the service index for source 
https://XXXX.pkgs.visualstudio.com/_packaging/XXXX/nuget/v3/index.json.
error:   Response status code does not indicate success: 401 (Unauthorized).

The dotnet list package --outdated doesn't support the --interactive flag.

Ginsberg-2:TS.XXXX.Api user$ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   2.2.104
 Commit:    73f036d4ac

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.14
 OS Platform: Darwin
 RID:         osx.10.14-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.2.104/

Host (useful for support):
  Version: 2.2.2
  Commit:  a4fd7b2c84


    .NET Core SDKs installed:
      2.1.4 [/usr/local/share/dotnet/sdk]
      2.1.503 [/usr/local/share/dotnet/sdk]
      2.2.104 [/usr/local/share/dotnet/sdk]
    
    .NET Core runtimes installed:
      Microsoft.AspNetCore.All 2.1.7 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
      Microsoft.AspNetCore.All 2.2.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
      Microsoft.AspNetCore.App 2.1.7 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
      Microsoft.AspNetCore.App 2.2.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
      Microsoft.NETCore.App 2.0.5 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
      Microsoft.NETCore.App 2.1.7 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] .  
      Microsoft.NETCore.App 2.2.2 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
    
    To install additional .NET Core runtimes or SDKs:
      https://aka.ms/dotnet-download

$profilePath is not resolved correctly in Windows Docker container

I have been trying to connect to my company's private nuget feed from inside a docker container and struggled to make it work.
In the end I found that there was an bug in the copying of the extracted files: they were copied to the folder where the script was run from instead of the UserProfile folder.

Checking the content of [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) in the intermediate container shows that it is empty (while it should be 'C;\Users\ContainerUser').
The base image I used is mcr.microsoft.com/dotnet/core/sdk:3.0

Workaround:

Changing $profilePath=System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) to $profilePath="C:\Users\ContainerUser\" made it work in my case.

dotnet restore --interactive fails with SSL errors on WSL

Hi Guys-

I'm running WSL (Pengwin) on Win10. I've installed the credprovider. (Though the plugin dir ended up being ~/.nuget/NuGet/plugins). When I run dotnet restore --interactive, I get:

/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :     [CredentialProvider]Failed to acquire session token: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.TypeInitializationException: The type initializer for 'SslMethods' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Ssl' threw an exception. ---> System.TypeInitializationException: The type initializer for 'SslInitializer' threw an exception. ---> Interop+Crypto+OpenSslCryptographicException: error:0E076071:configuration file routines:MODULE_RUN:unknown module name [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at Interop.SslInitializer..cctor() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    --- End of inner exception stack trace --- [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at Interop.Ssl..cctor() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    --- End of inner exception stack trace --- [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at Interop.Ssl.SslV2_3Method() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at Interop.Ssl.SslMethods..cctor() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    --- End of inner exception stack trace --- [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at Interop.OpenSsl.AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SafeDeleteSslContext..ctor(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslStreamPal.HandshakeInternal(SafeFreeCredentials credential, SafeDeleteContext& context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    --- End of inner exception stack trace --- [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__47_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    --- End of inner exception stack trace --- [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.ValueTask`1.get_Result() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.ValueTask`1.get_Result() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Threading.Tasks.ValueTask`1.get_Result() [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at NuGetCredentialProvider.CredentialProviders.Vsts.AuthUtil.GetResponseHeadersAsync(Uri uri, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at NuGetCredentialProvider.CredentialProviders.Vsts.AuthUtil.GetAadAuthorityUriAsync(Uri uri, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at NuGetCredentialProvider.CredentialProviders.Vsts.VstsCredentialProvider.HandleRequestAsync(GetAuthenticationCredentialsRequest request, CancellationToken cancellationToken) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :    at NuGetCredentialProvider.RequestHandlers.GetAuthenticationCredentialsRequestHandler.HandleRequestAsync(GetAuthenticationCredentialsRequest request) [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error : Unable to load the service index for source https://mscatapult.pkgs.visualstudio.com/_packaging/FpgaTools/nuget/v3/index.json. [/mnt/c/code/HWBuild/hwbuild.sln]
/usr/share/dotnet/sdk/2.2.300/NuGet.targets(121,5): error :   Response status code does not indicate success: 401 (Unauthorized). [/mnt/c/code/HWBuild/hwbuild.sln]

I'm not sure where to go from here. Is the credprovider not compatible with WSL or am I missing a package...? Is this even a credprovider issue or should I submit this to the .net core team?

Corrupted 'SessionTokenCache.dat' produces inactionable, unrecoverable 'The data is invalid' errors

Overview

I installed the cred provider to interact with an Azure DevOps packages feed. All was well.

At some point (possibly after a Blue Screen, though I'm not sure), all of my nuget commands started failing with the following error message.


   at NuGet.Protocol.Plugins.OutboundRequestContext`1.HandleFault(Message fault)
   at NuGet.Protocol.Plugins.MessageDispatcher.OnMessageReceived(Object sender, MessageEventArgs e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at NuGet.Protocol.Plugins.StandardOutputReceiver.OnLineRead(Object sender, LineReadEventArgs e)
   --- End of inner exception stack trace ---

The error didn't go away after re-runs and a reboot.
The errors provided no hint as to what the issue was or how it could be resolved.

After debugging for a while, I was able to trace the error to the following call stack:

 	credentialprovider.microsoft.exe!NuGetCredentialProvider.Util.EncryptedFile.ReadFileBytes(string, bool) Line 17	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.Util.SessionTokenCache.ReadFileBytes() Line 85	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.Util.SessionTokenCache.Cache.get() Line 27	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.Util.SessionTokenCache.TryGetValue(System.Uri, out string) Line 53	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.RequestHandlers.GetAuthenticationCredentialsRequestHandler.TryCache(NuGet.Protocol.Plugins.GetAuthenticationCredentialsRequest, out string) Line 149	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.RequestHandlers.GetAuthenticationCredentialsRequestHandler.HandleRequestAsync(NuGet.Protocol.Plugins.GetAuthenticationCredentialsRequest) Line 63	C#
 	credentialprovider.microsoft.exe!NuGetCredentialProvider.Program.Main(string[]) Line 155	C#

It looks like my %LocalAppData%\MicrosoftCredentialProvider\SessionTokenCache.dat file was corrupted somehow, leading to these errors.

Repro

  1. Use the cred provider to install a package
  2. Use a text editor to tweak the contents of %LocalAppData%\MicrosoftCredentialProvider\SessionTokenCache.dat
  3. Try to install another package using the cred provider

Expected behavior

The tool should ideally detect that the file is corrupted and recreate it. That failing, it should at least log something like 'File X contains invalid data.'

"A task was canceled" exception with CredentialProvider.Microsoft.exe v0.1.15

Our AzureDevOps build pipeline continues to see "System.Threading.Tasks.TaskCanceledException: A task was canceled." exceptions during NuGet restore, similar to #77, but we have version 0.1.15 that contains the fix for that issue.

We are using NuGet.exe v4.9.4 on AzureDevOps, installed using the NuGetToolInstaller@0 and performing a Restore using NuGetCommand@2, v2.150.0.

From the build logs, here's the NuGet.exe invocation:

Detected NuGet version 4.9.4.5839 / 4.9.4+ed6e2dca9391d13b431f4eff58c5194f0ebcee13
SYSTEMVSSCONNECTION exists true
[command]C:\BA\_tool\NuGet\4.9.4\x64\nuget.exe restore "C:\BA\8139\s\SpatialServices\SpatialServices API - Windows.sln" -Verbosity Detailed -NonInteractive -ConfigFile C:\BA\8139\s\SpatialServices\nuget.config
NuGet Version: 4.9.4.5839
MSBuild auto-detection: using msbuild version '15.9.21.664' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.

Here's the output from the CredentialProvider.Microsoft.exe showing version information:

Using C:\BA\_tasks\NuGetCommand_333b11bd-d341-40d9-afcf-b32d5ce6f23b\2.150.0\CredentialProviderV2\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe as a credential provider plugin.
    [CredentialProvider.175929]Time elapsed in milliseconds after sending response 'Request' 'GetOperationClaims': 28
    [CredentialProvider.175929]Running in plug-in mode
    [CredentialProvider.175929]Handling 'Request' 'Initialize'. Time elapsed in ms: 7 - Payload: {"ClientVersion":"4.9.4","Culture":"en-US","RequestTimeout":"00:00:05"}
    [CredentialProvider.175929]Time elapsed in milliseconds after sending response 'Request' 'Initialize': 10
    [CredentialProvider.175929]Sending response: 'Request' 'Initialize'. Time elapsed in ms: 9
    [CredentialProvider.175929]Command-line v0.1.15: "C:\BA\_tasks\NuGetCommand_333b11bd-d341-40d9-afcf-b32d5ce6f23b\2.150.0\CredentialProviderV2\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe" -Plugin
    [CredentialProvider.175929]Handling 'Request' 'GetOperationClaims'. Time elapsed in ms: 1 - Payload: {}
    [CredentialProvider.175929]Sending response: 'Request' 'GetOperationClaims'. Time elapsed in ms: 12
    [CredentialProvider.175929]Handling 'Request' 'SetLogLevel'. Time elapsed in ms: 1 - Payload: {"LogLevel":"Debug"}
    [CredentialProvider]Sending response: 'Request' 'SetLogLevel'. Time elapsed in ms: 3
    [CredentialProvider]Time elapsed in milliseconds after sending response 'Request' 'SetLogLevel': 6

And the unhandled exception that fails builds:

Unhandled Exception: System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Plugins.MessageDispatcher.<DispatchWithNewContextAsync>d__26`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Plugins.SymmetricHandshake.<HandshakeAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Plugins.Connection.<ConnectAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Plugins.PluginFactory.<CreateFromCurrentProcessAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGetCredentialProvider.Program.<Main>d__11.MoveNext() in E:\A\_work\616\s\CredentialProvider.Microsoft\Program.cs:line 133
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGetCredentialProvider.Program.<Main>(String[] args)

[YAML-BUILD] 401 when building Dockerfile in Build Agent (Interactive?)

Passing in the $(System.AccessToken) and using a custom NuGet.config, I'm seeing this error in the build:

Error

/usr/share/dotnet/sdk/2.2.104/NuGet.targets(114,5): warning : The plugin credential provider could not acquire credentials. Authentication may require manual action. Consider re-running the command with --interactive for `dotnet`, /p:NuGetInteractive="true" for MSBuild or removing the -NonInteractive switch for `NuGet` [/src/Solution/Project.csproj]
/usr/share/dotnet/sdk/2.2.104/NuGet.targets(114,5): error : Unable to load the service index for source https://pkgs.dev.azure.com/1234567890/_packaging/0987654321/nuget/v3/index.json. [/src/Solution/Project.csproj]
/usr/share/dotnet/sdk/2.2.104/NuGet.targets(114,5): error :   Response status code does not indicate success: 401 (Unauthorized). [/src/Solution/Project.csproj]

Build YAML

variables:
  PAT: $(System.AccessToken)
...

- task: DockerCompose@0
  displayName: Container build
  inputs:
    action: Build services
    containerregistrytype: Azure Container Registry
    azureSubscriptionEndpoint: $(azureSubscriptionEndpoint)
    azureContainerRegistry: $(azureContainerRegistry)
    dockerComposeFile: $(projectRootPath)/docker-compose.yml
    additionalDockerComposeFiles: docker-compose.az-build.yml
  env:
    DOCKER_REGISTRY: $(azureContainerRegistry)/
    PAT: $(PAT)

Dockerfile

FROM microsoft/dotnet:2.2-sdk AS sdk-base

ARG FEED_URL
ARG PAT

FROM microsoft/dotnet:2.2-aspnetcore-runtime-alpine AS runtime-base

FROM sdk-base AS build

ARG FEED_URL
ARG PAT

# Install the Credential Provider to configure the access
RUN wget -qO- https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash

# Configure the environment variables
ENV NUGET_CREDENTIALPROVIDER_SESSIONTOKENCACHE_ENABLED true
ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS "{\"endpointCredentials\": [{\"endpoint\":\"${FEED_URL}\", \"password\":\"${PAT}\"}]}"

WORKDIR /src
COPY ["Solution/Project.csproj", "Solution/"]
COPY ["NuGet.config", "."]

RUN dotnet restore "Solution/Project.csproj" --configfile ./NuGet.config -v quiet

NuGet.config

<configuration>
  <packageSources>
    <clear />
    <add key="0987654321" value="https://pkgs.dev.azure.com/1234567890/_packaging/0987654321/nuget/v3/index.json." protocolVersion="3" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
  <activePackageSource>
    <add key="All" value="(Aggregate source)" />
  </activePackageSource>
</configuration>

dotnet restore --interactive does not work On prem

Environment

  • Using Ubuntu 18.04.1 LTS (Bionic Beaver) on a Windows host.
  • Connecting to a TFS 2017 Update 2 Server.
  • Installed latest Nuget.exe, .Net Core v2.1.6 (SDK 2.1.500)
  • Installed Microsoft.NuGet.CredentialProvider and verified content in $HOME\.nuget\plugins

Issues

  • dotnet restore --interactive does not prompt
  • dotnet restore with nuget.config file containing PAT token throws exception
/usr/share/dotnet/sdk/2.1.500/NuGet.targets(114,5): error : Unable to load the service index for source https://[REDACTED]/nuget/v3/index.json. [REDACTED]
/usr/share/dotnet/sdk/2.1.500/NuGet.targets(114,5): error :   GSSAPI operation failed with error - An invalid status code was supplied (Invalid value in argument). [REDACTED]
  • dotnet restore without specifying PAT token in nuget.config throws exception
/usr/share/dotnet/sdk/2.1.500/NuGet.targets(114,5): error : Unable to load the service index for source https://REDACTED/nuget/v3/index.json. [REDACTED]
/usr/share/dotnet/sdk/2.1.500/NuGet.targets(114,5): error :   GSSAPI operation failed with error - An invalid status code was supplied (SPNEGO cannot find mechanisms to negotiate). [REDACTED]

Please advise on any know issues / workaround to get a dotnet restore working against a TFS private package feed.

Continuous prompting for credentials on Linux / VS Code

I've installed the credential provider using the one-shot script and verified the locations of the tooling as provided in the description. I assume the correct behavior for the credential provider is to prompt once and terminate. When I run dotnet restore --interactive in either an Ubuntu terminal or in VS Code terminal it results in a continuous loop of browser authentications with generated tokens (i.e. repeated requests for authentication with different tokens as shown in the screenshot below). The command never completes unless I leave it running and don't respond within 90 seconds. For each cycle of authentication, I do receive an email confirmation from Azure DevOps for each new token. Any help on this would be appreciated as it's becoming a blocking issue.

OS: Ubuntu 19.04
VS Code: 1.37.1
.NET Core 2.2

image

installcredprovider.ps1 -force doesn't actually overwrite previous contents

== Repro ==

  1. Have an older version of the cred provider installed (e.g. 0.1.11.0)
  2. Run installCredProvider.ps1 -AddNetFx -Force
  3. Check the installed version (e.g. via (get-item -Path "$Env:userprofile\.nuget\plugins\netfx\CredentialProvider.Microsoft\CredentialProvi der.Microsoft.exe").VersionInfo | Format-List -Force

The version will still be the old version instead of whatever the current version is (currently 0.1.15.0)

Bundle with nuget

When I download git for Windows, then it has built-in support for 2FA for different providers like GitHub or VSTS.

Wouldn't it make sense to include this credential provider directly in the main nuget distribution? This would save projects from including installation instructions in their README files on how to get started with private Azure NuGet feeds. I consider this a problem, especially since this is only required when using the command line or VS Code. Opening a project in Visual Studio works out of the box as it has built-in integration with private Azure NuGet feeds and doesn't require any extra steps.

Unable to use credential provider in a multistage docker build using a dotnet core 3.0 image

I start my multistage docker builds with FROM mcr.microsoft.com/dotnet/core/sdk:3.0 as I'm evaluating .NET Core 3.0.0-preview5. The code I build has dependencies in a private NuGet feed so I use the following along with ARG VSS_NUGET_EXTERNAL_FEED_ENDPOINTS to supply the required auth info:

FROM mcr.microsoft.com/dotnet/core/sdk:3.0
ARG VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

# support private nuget feeds using the env VSS_NUGET_EXTERNAL_FEED_ENDPOINTS
RUN wget https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh \
   && chmod +x installcredprovider.sh \
   && ./installcredprovider.sh

Feed authorization has worked in the past when the base image is a sdk:2.2 or similar tag. The problem with using the sdk:3.0 tag is that the credentials provider is dependent on .NET Core 2.1 which is unavailable in the base docker image.

Is there a version of the credential provider built for .NET Core 3.0.0 previews, preferably the latest?

Cred provider does not work with .net sdk 3.0.100

Install .net sdk 3.0.100.

Set NUGET_PLUGINS_PATH to point to the cred provider location. Use dotnet restore to restore packages. Fails with:

It was not possible to find any compatible framework version
The specified framework 'Microsoft.NETCore.App', version '2.1.0' was not found.

  • Check application dependencies and target a framework version installed at:
    /usr/share/dotnet/
  • Installing .NET Core prerequisites might help resolve this problem:
    https://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  • The .NET Core framework and SDK can be installed from:
    https://aka.ms/dotnet-download
  • The following versions are installed:
    3.0.0-preview-27122-01 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]
    1>/usr/share/dotnet/sdk/3.0.100-preview-009812/NuGet.targets(114,5): error : Broken pipe [/root/code/code1/code1.csproj]
    System.IO.IOException: Broken pipe
    at System.IO.FileStream.WriteNative(ReadOnlySpan1 source) at System.IO.FileStream.FlushWriteBuffer() at System.IO.FileStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.StreamWriter.CloseStreamFromDispose(Boolean disposing) at System.IO.StreamWriter.Dispose(Boolean disposing) at System.IO.TextWriter.Dispose() at NuGet.Protocol.Plugins.Sender.Dispose() at NuGet.Protocol.Plugins.Connection.Dispose() at NuGet.Protocol.Plugins.Plugin.Dispose() at NuGet.Protocol.Plugins.PluginFactory.CreatePluginAsync(String filePath, IEnumerable1 arguments, IRequestHandlers requestHandlers, ConnectionOptions options, CancellationToken sessionCancellationToken)
    at NuGet.Protocol.Plugins.PluginFactory.GetOrCreateAsync(String filePath, IEnumerable`1 arguments, IRequestHandlers requestHandlers, ConnectionOptions options, CancellationToken sessionCancellationToken)
    at NuGet.Protocol.Core.Types.PluginManager.<>c__DisplayClass24_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---

After that I removed the NUGET_PLUGINS_PATH location and it worked well. So, there is something wrong with nuget talking to plugin for the first time.

Need to revert this commit once resolved.

Random failure to authenticate to Azure DevOps using dotnet tool

The credential provider fails to properly authenticate with an Azure DevOps feed about 50% of the time as shown below:

dotnet-tool-install-randomly-fails-post

A Fiddler trace shows that the "Authorization" header contains invalid credentials for the times that it fails:

GET https://REDACTED/_packaging/REDACTED/nuget/v3/flat2/REDACTED/index.json HTTP/1.1
X-NuGet-Session-Id: REDACTED
User-Agent: NuGet .NET Core MSBuild Task/4.9.0 (Microsoft Windows 10.0.17134 )
X-NuGet-Client-Version: 4.9.0
Accept-Language: en-US
Accept-Encoding: gzip, deflate
Authorization: Basic Og==
Host: REDACTED

Decoding "Og==" in Base64 results in ":"

InstallCredentialProvider.ps1 fails with dotnet sdk 3.0 docker image

I'm trying to install Credential Provider through dockerfile but looks like it is failing for asp.net core sdk 3.0 (mcr.microsoft.com/dotnet/core/sdk:3.0) docker image.

The script InstallCredentialProvider.ps1 is https://github.com/microsoft/artifacts-credprovider/blob/master/helpers/installcredprovider.ps1

Step 12/23 : RUN pwsh InstallCredentialProvider.ps1
---> Running in 7c6e24ab258f
Fetching release https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/latest
Using Microsoft.NetCore2.NuGet.CredentialProvider.zip
Creating temp directory for the Credential Provider zip: C:\Windows\TEMP\CredProviderZip

 Directory: C:\Windows\TEMP
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 9/5/2019 11:02 AM CredProviderZip
Downloading https://github.com/microsoft/artifacts-credprovider/releases/download/0.1.18/Microsoft.NetCore2.NuGet.CredentialProvider.zip to C:\Windows\TEMP\CredProviderZip\Microsoft.NuGet.CredentialProvider.zip
Extracting zip to the Credential Provider temp directory
Copying Credential Provider to .nuget\plugins
Copy-Item : Cannot find path 'C:\Windows\TEMP\CredProviderZip\plugins\netcore\CredentialProvider.Microsoft' because it does not exist.
At C:\src\InstallCredentialProvider.ps1:128 char:1
+ Copy-Item ([System.IO.Path]::Combine($tempZipLocation, "plugins", $lo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Windows\TEMP\Cre…lProvider.Microsoft:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
The command 'cmd /S /C pwsh InstallCredentialProvider.ps1' returned a non-zero code: 1

nuget.exe install prompts for username and password instead of using this cred provider

I have run https://raw.githubusercontent.com/microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1 on my machine and 0.1.18.0 of the credential provider is installed.

Yet when I try to use nuget install I just get a username/password prompt:

tools\5.0.2\nuget.exe install -source https://devdiv.pkgs.visualstudio.com/DefaultCollection/_packaging/MicroBuildToolset/nuget/v3/index.json A
Feeds used:
  https://devdiv.pkgs.visualstudio.com/DefaultCollection/_packaging/MicroBuildToolset/nuget/v3/index.json

Installing package 'A' to 'D:\git\lib.template'.
MSBuild auto-detection: using msbuild version '16.300.19.37701' from 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Int.Preview\MSBuild\Current\Bin'.
Please provide credentials for: https://devdiv.pkgs.visualstudio.com/DefaultCollection/_packaging/MicroBuildToolset/nuget/v3/index.json
UserName: Password:

Interactive UI question

I'm looking to migrate from Microsoft.VisualStudio.Services.NuGet.CredentialProvider, but I'm a bit unclear as to what UI I should get when running in interactive mode.

Should I see a pop-up dialog (like I would get with the old provider), or is it just a console-based prompt?

Or does it vary depending on whether I run dotnet restore or nuget restore?

'dotnet restore' unhandled exception with NuGetCredentialProvider

Hey team,

I'm not sure if this is an issue with the dotnet CLI or with the credential provider. I'll try this repository first. I've also reviewed the other open issues and it this doesn't appear to be related.

We are using Azure Artifacts and restoring packages in a docker container:

WORKDIR /nuget_cache_warmer
COPY **/*.csproj ./
RUN for f in ./*.csproj; do dotnet restore $f --source $NUGET_SOURCE --source https://api.nuget.org/v3/index.jsonl; done

This is our base image: FROM microsoft/dotnet:2.1-sdk

Intermittently, I start to see:

Unhandled Exception:  [0m [91mSystem.Threading.Tasks.TaskCanceledException: A task was canceled.
NuGet.Protocol.Plugins.MessageDispatcher.DispatchWithNewContextAsync[TOutgoing,TIncoming](IConnection connection, MessageType type, MessageMethod method, TOutgoing payload, CancellationToken cancellationToken) at NuGet.Protocol.Plugins.SymmetricHandshake.HandshakeAsync(CancellationToken cancellationToken) at NuGet.Protocol.Plugins.Connection.ConnectAsync(CancellationToken cancellationToken)
at NuGet.Protocol.Plugins.PluginFactory.CreateFromCurrentProcessAsync(IRequestHandlers requestHandlers, ConnectionOptions options, CancellationToken sessionCancellationToken)
at NuGetCredentialProvider.Program.Main(String[] args)
at NuGetCredentialProvider.Program.<Main>(String[] args)

This happens more than once during the restore processing, but not for every .csproj file.

What is interesting compared to other issues is the restore process will complete, and I can run the next docker step to build my project successfully.

If it matters, the docker build is running on a Linux TeamCity agent. If I run dotnet restore --disable-parallel, the exception does not occur, however the restore takes twice as long (as expected).

Since I can still restore successfully this isn't a huge problem, though I thought I'd report it.

Nuget.exe prompting for credentials on every restore

Hello,

I have the credential provider installed at %userprofile%/.nuget/plugins. It works fine for the dotnet CLI. I have used the --interactive switch once and it has saved my credentials and reuses the cached creds on subsequent dotnet operations.

I'm now trying to have nuget.exe cache my credentials. However, on each nuget restore run, it prompts me for my credentials when trying to authenticate against Azure Artifacts.

Tool versions:

MSBuild: 15.9.21.664
nuget.exe: 4.9.4.5839

I noticed when running nuget restore, the tool outputs this:

MSBuild auto-detection: using msbuild version '15.9.21.664' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin'.

Is it likely I need to use interactive mode with msbuild first before I can use nuget.exe without providing credentials?

I'm running msbuild /t:restore /p:nugetInteractive=true but it doesn't seem to be restoring any of my packages. I'll keep trying and in the meantime, I'm hoping to hear back from one of the contributors here.

Thanks for your help and thanks for developing this great tool :)

Change the Azure Artifacts download to this

Currently when you go to Azure Artifacts and click Connect to feed, you see this:

image

Given that Gen 1 credential providers are soon to be deprecated, shouldn't the bits in this repo be what is linked to from there?

Edit: apologies if this is the wrong place to raise it

Unhandled Exception: System.IO.FileNotFoundException

Installed Cred Provider with automated PowerShell script.

  1. NuGet.exe 4.9.2 does not find the plugin WITHOUT setting the NUGET_PLUGIN_PATHS env var, so the convention based lookup is broken.

Then I set the env var:

$env:NUGET_PLUGIN_PATHS="C:\Users\OSKAR207adm\.nuget\plugins\netcore\CredentialProvider.Microso
ft\CredentialProvider.Microsoft.dll"
  1. After setting the env var and running a push command, the credential provider bombs out:
PS C:\Users\OSKAR207adm> & "C:\BuildAgent\tools\NuGet.CommandLine.4.9.2\tools\NuGet.exe" push "<package>"
 vsts -Source <feed_url> -Verbosity detailed
NuGet Version: 4.9.2.5706
Using C:\Users\OSKAR207adm\.nuget\plugins\netcore\CredentialProvider.Microsoft\CredentialProvider.Microsoft.dll as a cre
dential provider plugin.

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.1.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Unable to load the service index for source <feed_url>.
  A task was canceled.
NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source <feed_url>.
 ---> System.Threading.Tasks.TaskCanceledException: A tas
k was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.TimeoutUtility.<StartWithTimeout>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.HttpRetryHandler.<SendAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.HttpSource.<GetThrottledResponse>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.HttpSource.<>c__DisplayClass14_0`1.<<GetAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Common.ConcurrencyUtilities.<ExecuteWithFileLockedAsync>d__2`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.HttpSource.<GetAsync>d__14`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
   --- End of inner exception stack trace ---
   at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.ServiceIndexResourceV3Provider.<TryCreate>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.PackageUpdateResourceV3Provider.<TryCreate>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__15`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.CommandRunnerUtility.<GetPackageUpdateResource>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Commands.PushRunner.<Run>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.CommandLine.PushCommand.<ExecuteCommandAsync>d__32.MoveNext()

.NET Core SDK version: 2.2.103

Case sensitive comparison for endpoint credentials

There is a case sensitive comparison on line 111 in VstsBuildTaskServiceEndpointCredentialProvider.cs that leads to unbeing able to authorization for a certain endpoint if something is in the wrong case. This comparison should be made case insensitive.

Question: How do you force token acquisition

I just installed the credential provider via the helper script on macOS. I'm now trying to install a global tool from a private azure feed, but it's coming up with a package not found error. I suspect this is because I haven't yet acquired a token. The README says to run dotnet restore --interactive, but I don't have a project against which I can restore (since I'm trying to install a global tool). Is there another way to force it to acquire a token?

Provider does not seem to work with latest SDK docker image

The readme is not very clear on what the prerequisites are for this on Linux -- or, indeed, whether or not this even works with dotnet on Linux. I have a container based on microsoft/dotnet:2.1-sdk which contains version 2.1.402 of the SDK according to dotnet, I have run the install script and /root/.nuget/plugins contains the provider, but:

  • Setting VSS_NUGET_EXTERNAL_FEED_ENDPOINTS does not seem to have any effect (even with the correct syntax, as per #33)
  • Running dotnet restore --interactive project.csproj likewise fails with a 401 without ever prompting for anything.

There's no evidence that the plugin is being run, so I'm guessing my prerequisites are somehow wrong.

Windows Integrated Auth fails

All our users are not able to authenticate with our DevOps Artifacts feed.

[Verbose] [CredentialProvider]GET https://XXX
[Verbose] [CredentialProvider]Could not find AAD authority from headers, using default: https://login.microsoftonline.com
[Verbose] [CredentialProvider]Using AAD authority: https://login.microsoftonline.com/common
[Verbose] [CredentialProvider]Failed to acquire token from cache
[Verbose] [CredentialProvider]VstsCredentialProvider - Exception trying to generate VSTS/TFS token: https://XXX, message: password_required_for_managed_user: Password is required for managed user, stack:    at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenNonInteractiveHandler.PreTokenRequestAsync()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.RunAsync()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenCommonAsync(String resource, String clientId, UserCredential userCredential)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync(AuthenticationContext ctx, String resource, String clientId, UserCredential userCredential)
   at NuGetCredentialProvider.CredentialProviders.Vsts.AdalTokenProvider.AcquireTokenWithWindowsIntegratedAuth(CancellationToken cancellationToken) in E:\A\_work\203\s\CredentialProvider.Microsoft\CredentialProviders\Vsts\AdalTokenProvider.cs:line 98
   at NuGetCredentialProvider.CredentialProviders.Vsts.BearerTokenProvider.GetAsync(Uri uri, Boolean isRetry, Boolean isNonInteractive, Boolean canShowDialog, CancellationToken cancellationToken) in E:\A\_work\203\s\CredentialProvider.Microsoft\CredentialProviders\Vsts\BearerTokenProvider.cs:line 65
   at NuGetCredentialProvider.CredentialProviders.Vsts.VstsCredentialProvider.HandleRequestAsync(GetAuthenticationCredentialsRequest request, CancellationToken cancellationToken) in E:\A\_work\203\s\CredentialProvider.Microsoft\CredentialProviders\Vsts\VstsCredentialProvider.cs:line 70
[Verbose] [CredentialProvider]VstsCredentialProvider - Could not find credentials for https://XXX
[Information] [CredentialProvider]Username:
[Information] [CredentialProvider]Password:

Documentation request: Adding the credential provider for a VSTS / Azure DevOps agent

Hi there,

I'm attempting to set up our on-premise build agents to use the Credential Provider when restoring packages from our private Azure Artifacts feed. However it's not entirely clear from the documentation how you install the Credential Provider NuGet plugin in a way that the Network Service which runs the VSTS / Azure DevOps Agent service can use it.

Would much appreciate if you can update the docs with this info, as the Credential Provider seems like the perfect solution for this kind of environment.

Credential Provider is for Read-Only use cases?

I just have a question about this project.

Can this artifacts credential provider be used to push packages to our internal Azure Dev Ops Artefacts feed.

If not, can you point me in the right direction in how I can achieve this. Limitations are that I cannot use the yaml tasks to push packages, I should be able to do it from a script.

Concurrent CredentialProvider processes cause IOExceptions on SessionTokenCache.dat

Description

If SessionTokenCache.dat is not present & up-to-date, spawning multiple Nuget/CredentialProvider processes at once will lead to failures.

There are two specific problems here:

  1. The failing processes will emit output like [Error] [CredentialProvider]Failed to acquire session token: System.IO.IOException: The process cannot access the file '%userprofile%\AppData\Local\MicrosoftCredentialProvider\SessionTokenCache.dat' because it is being used by another process.
    1. Somewhat oddly, the error is written to stdout instead of stderr
  2. The failing processes still return a successful exit code (0)

Note that this does NOT seem to cause SessionTokenCache.dat to become corrupted. Subsequent runs seem to work just fine.

Repro

The following C# snippet will consistently produce a few failures.

const int numProcesesToSpawn = 20;

string credentialProviderExe = Environment.ExpandEnvironmentVariables(@"%userprofile%\.nuget\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe");
string datFilePath = Environment.ExpandEnvironmentVariables(@"%LocalAppData%\MicrosoftCredentialProvider\SessionTokenCache.dat");
string feedUrl = "<my AzDev nuget feed url>";

if (File.Exists(datFilePath)) File.Delete(datFilePath);

Parallel.For(0, numProcesesToSpawn, (i) =>
{
    ProcessStartInfo startInfo = new ProcessStartInfo(credentialProviderExe, $"-N -U {feedUrl}");
    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardOutput = true;

    Process process = Process.Start(startInfo);
    process.WaitForExit();
    string stdOut = process.StandardOutput.ReadToEnd();

    if (stdOut.Contains("The process cannot access the file"))
    {
        Console.WriteLine($"Encountered failure. Exit code is {process.ExitCode}. Stdout = '{stdOut}'");
    }
});

Console.WriteLine("Done");

Symptoms

Sample CredentialProvider error message:

[Information] [CredentialProvider]VstsCredentialProvider - Acquired bearer token using 'ADAL Windows Integrated Authentication'
[Information] [CredentialProvider]VstsCredentialProvider - Attempting to exchange the bearer token for an Azure DevOps session token.
[Error] [CredentialProvider]Failed to acquire session token: System.IO.IOException: The process cannot access the file 'C:\Users\bberger\AppData\Local\MicrosoftCredentialProvider\SessionTokenCache.dat' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)
   at NuGetCredentialProvider.Util.EncryptedFile.WriteFileBytes(String filePath, Byte[] bytes, Boolean writeUnencrypted) in E:\A\_work\467\s\CredentialProvider.Microsoft\Util\EncryptedFile.cs:line 36
   at NuGetCredentialProvider.Util.SessionTokenCache.set_Item(Uri key, String value) in E:\A\_work\467\s\CredentialProvider.Microsoft\Util\SessionTokenCache.cs:line 40
   at NuGetCredentialProvider.RequestHandlers.GetAuthenticationCredentialsRequestHandler.<HandleRequestAsync>d__5.MoveNext() in E:\A\_work\467\s\CredentialProvider.Microsoft\RequestHandlers\GetAuthenticationCredentialsRequestHandler.cs:line 91
[Information] [CredentialProvider]Username:
[Information] [CredentialProvider]Password:

Sample nuget error

Restoring NuGet package NETStandard.Library.2.0.3.
MSBuild auto-detection: using msbuild version '15.9.21.664' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'.
    [CredentialProvider]VstsCredentialProvider - Attempting to exchange the bearer token for an Azure DevOps session token.
    [CredentialProvider]VstsCredentialProvider - Acquired bearer token using 'ADAL Windows Integrated Authentication'
WARNING: Unable to find version '2.0.3' of package 'NETStandard.Library'.
  D:\nugetcache\.pkgref: Package 'NETStandard.Library.2.0.3' is not found on source 'D:\nugetcache\.pkgref'.
  <my AzDev feed>: Unable to load the service index for source <my AzDev feed>.
  Response status code does not indicate success: 401 (Unauthorized).
 
WARNING: Unable to find version '2.0.3' of package 'NETStandard.Library'.
  D:\nugetcache\.pkgref: Package 'NETStandard.Library.2.0.3' is not found on source 'D:\nugetcache\.pkgref'.
  <my AzDev feed>: Unable to load the service index for source <my AzDev feed>.
  Response status code does not indicate success: 401 (Unauthorized).
 
 
NuGet Config files used:
    D:\o1\dev\NuGet.Config
    %AppData%\Roaming\NuGet\NuGet.Config
    C:\Program Files (x86)\NuGet\Config\Microsoft.VisualStudio.Offline.config
 
Feeds used:
    D:\nugetcache\.pkgref
    <my AzDev feed>
 
    [CredentialProvider]Failed to acquire session token: System.IO.IOException: The process cannot access the file '%LocalAppData%\MicrosoftCredentialProvider\SessionTokenCache.dat' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean
 useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)
   at NuGetCredentialProvider.Util.EncryptedFile.WriteFileBytes(String filePath, Byte[] bytes, Boolean writeUnencrypted) in E:\A\_work\467\s\CredentialProvider.Microsoft\Util\EncryptedFile.cs:line 36
   at NuGetCredentialProvider.Util.SessionTokenCache.set_Item(Uri key, String value) in E:\A\_work\467\s\CredentialProvider.Microsoft\Util\SessionTokenCache.cs:line 40
   at NuGetCredentialProvider.RequestHandlers.GetAuthenticationCredentialsRequestHandler.d__5.MoveNext() in E:\A\_work\467\s\CredentialProvider.Microsoft\RequestHandlers\GetAuthenticationCredentialsRequestHandler.cs:line
 91
Errors in packages.config projects
    Unable to find version '2.0.3' of package 'NETStandard.Library'.
      D:\nugetcache\.pkgref: Package 'NETStandard.Library.2.0.3' is not found on source 'D:\nugetcache\.pkgref'.
      <my AzDev feed>: Unable to load the service index for source <my AzDev feed>.
      Response status code does not indicate success: 401 (Unauthorized).

How to set VSS_NUGET_EXTERNAL_FEED_ENDPOINTS correctly

I'm trying to set VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable but it looks like no effect.

Here are the steps to reproduce my problem.

Machine A:

  1. Install NuGet.exe and CredentialProvider.VSS.exe

    choco install nuget.commandline nuget-credentialprovider-vss -y
  2. Create new nuget.config file

    dotnet new nuget
  3. Add my Azure Artifacts NuGet feed

    nuget sources add -Name {YourOrg} -Source https://{YourOrg}.pkgs.visualstudio.com/_packaging/{YourProject}/nuget/v3/index.json
  4. Try pass the authenticate

    nuget list
  5. Generate PAT by the following command. Copy the "Password" property's value as PAT.

    CredentialProvider.VSS.exe -U https://{YourOrg}.pkgs.visualstudio.com/_packaging/{YourProject}/nuget/v3/index.json

Machine B:

  1. Install NuGet.exe and CredentialProvider.VSS.exe

    choco install nuget.commandline nuget-credentialprovider-vss -y
  2. Create new nuget.config file

    dotnet new nuget
  3. Add my Azure Artifacts NuGet feed

    nuget sources add -Name {YourOrg} -Source https://{YourOrg}.pkgs.visualstudio.com/_packaging/{YourProject}/nuget/v3/index.json
  4. Setup VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable. The [PAT] is what I generated at Machine A.

    set VSS_NUGET_EXTERNAL_FEED_ENDPOINTS={"endpointCredentials": [{"endpoint":"https://{YourOrg}.pkgs.visualstudio.com/_packaging/{YourProject}/nuget/v3/index.json", "username":"VssSessionToken", "password":"[PAT]"}]}
  5. Try pass the authenticate but this doesn't read VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable!

    nuget list

I expected the pass authentication because I already set correct VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable! Am I do something wrong?

nuget.config interfere with VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

running on linux (docker) .
using microsoft/dotnet:2.1.403-sdk
and https://github.com/Microsoft/artifacts-credprovider/releases/download/...

VSS_NUGET_EXTERNAL_FEED_ENDPOINTS is set up correctly to authenticated to a tfs 2017 nuget feed.

If I add a nuget.config in the restore directory, something gets broken and I get a 401 ...
If I remove the nuget.config it does work back again .

Note that it does not work even if I put corect credentials (pat token) in the nuget.config
("ems" is an on premise tfs 2017 nuget feed)

Is nuget.config supported somehow in this scenario ? If it is not, it should be ignored altogether.
p.s. : the nuget.config is fine since I was using it nuget.exe for restore (but had to pull mono in the build) container).

installcredprovider.sh doesn't work

ERROR: Unable to find url in JSON response. Response: {

  "url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/16072424",

  "assets_url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/16072424/assets",

  "upload_url": "https://uploads.github.com/repos/Microsoft/artifacts-credprovider/releases/16072424/assets{?name,label}",

  "html_url": "https://github.com/Microsoft/artifacts-credprovider/releases/tag/0.1.15",

  "id": 16072424,

  "node_id": "MDc6UmVsZWFzZTE2MDcyNDI0",

  "tag_name": "0.1.15",

  "target_commitish": "master",

  "name": "0.1.15",

  "draft": false,

  "author": {

    "login": "satbai",

    "id": 24945574,

    "node_id": "MDQ6VXNlcjI0OTQ1NTc0",

    "avatar_url": "https://avatars0.githubusercontent.com/u/24945574?v=4",

    "gravatar_id": "",

    "url": "https://api.github.com/users/satbai",

    "html_url": "https://github.com/satbai",

    "followers_url": "https://api.github.com/users/satbai/followers",

    "following_url": "https://api.github.com/users/satbai/following{/other_user}",

    "gists_url": "https://api.github.com/users/satbai/gists{/gist_id}",

    "starred_url": "https://api.github.com/users/satbai/starred{/owner}{/repo}",

    "subscriptions_url": "https://api.github.com/users/satbai/subscriptions",

    "organizations_url": "https://api.github.com/users/satbai/orgs",

    "repos_url": "https://api.github.com/users/satbai/repos",

    "events_url": "https://api.github.com/users/satbai/events{/privacy}",

    "received_events_url": "https://api.github.com/users/satbai/received_events",

    "type": "User",

    "site_admin": false

  },

  "prerelease": false,

  "created_at": "2019-03-12T20:54:18Z",

  "published_at": "2019-03-12T21:18:31Z",

  "assets": [

    {

      "url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/assets/11496508",

      "id": 11496508,

      "node_id": "MDEyOlJlbGVhc2VBc3NldDExNDk2NTA4",

      "name": "Microsoft.NetCore2.NuGet.CredentialProvider.tar.gz",

      "label": null,

      "uploader": {

        "login": "satbai",

        "id": 24945574,

        "node_id": "MDQ6VXNlcjI0OTQ1NTc0",

        "avatar_url": "https://avatars0.githubusercontent.com/u/24945574?v=4",

        "gravatar_id": "",

        "url": "https://api.github.com/users/satbai",

        "html_url": "https://github.com/satbai",

        "followers_url": "https://api.github.com/users/satbai/followers",

        "following_url": "https://api.github.com/users/satbai/following{/other_user}",

        "gists_url": "https://api.github.com/users/satbai/gists{/gist_id}",

        "starred_url": "https://api.github.com/users/satbai/starred{/owner}{/repo}",

        "subscriptions_url": "https://api.github.com/users/satbai/subscriptions",

        "organizations_url": "https://api.github.com/users/satbai/orgs",

        "repos_url": "https://api.github.com/users/satbai/repos",

        "events_url": "https://api.github.com/users/satbai/events{/privacy}",

        "received_events_url": "https://api.github.com/users/satbai/received_events",

        "type": "User",

        "site_admin": false

      },

      "content_type": "application/x-gzip",

      "state": "uploaded",

      "size": 1248422,

      "download_count": 71,

      "created_at": "2019-03-12T21:18:17Z",

      "updated_at": "2019-03-12T21:18:18Z",

      "browser_download_url": "https://github.com/Microsoft/artifacts-credprovider/releases/download/0.1.15/Microsoft.NetCore2.NuGet.CredentialProvider.tar.gz"

    },

    {

      "url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/assets/11496507",

      "id": 11496507,

      "node_id": "MDEyOlJlbGVhc2VBc3NldDExNDk2NTA3",

      "name": "Microsoft.NetCore2.NuGet.CredentialProvider.zip",

      "label": null,

      "uploader": {

        "login": "satbai",

        "id": 24945574,

        "node_id": "MDQ6VXNlcjI0OTQ1NTc0",

        "avatar_url": "https://avatars0.githubusercontent.com/u/24945574?v=4",

        "gravatar_id": "",

        "url": "https://api.github.com/users/satbai",

        "html_url": "https://github.com/satbai",

        "followers_url": "https://api.github.com/users/satbai/followers",

        "following_url": "https://api.github.com/users/satbai/following{/other_user}",

        "gists_url": "https://api.github.com/users/satbai/gists{/gist_id}",

        "starred_url": "https://api.github.com/users/satbai/starred{/owner}{/repo}",

        "subscriptions_url": "https://api.github.com/users/satbai/subscriptions",

        "organizations_url": "https://api.github.com/users/satbai/orgs",

        "repos_url": "https://api.github.com/users/satbai/repos",

        "events_url": "https://api.github.com/users/satbai/events{/privacy}",

        "received_events_url": "https://api.github.com/users/satbai/received_events",

        "type": "User",

        "site_admin": false

      },

      "content_type": "application/x-zip-compressed",

      "state": "uploaded",

      "size": 1262044,

      "download_count": 3767,

      "created_at": "2019-03-12T21:18:13Z",

      "updated_at": "2019-03-12T21:18:13Z",

      "browser_download_url": "https://github.com/Microsoft/artifacts-credprovider/releases/download/0.1.15/Microsoft.NetCore2.NuGet.CredentialProvider.zip"

    },

    {

      "url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/assets/11496506",

      "id": 11496506,

      "node_id": "MDEyOlJlbGVhc2VBc3NldDExNDk2NTA2",

      "name": "Microsoft.NuGet.CredentialProvider.tar.gz",

      "label": null,

      "uploader": {

        "login": "satbai",

        "id": 24945574,

        "node_id": "MDQ6VXNlcjI0OTQ1NTc0",

        "avatar_url": "https://avatars0.githubusercontent.com/u/24945574?v=4",

        "gravatar_id": "",

        "url": "https://api.github.com/users/satbai",

        "html_url": "https://github.com/satbai",

        "followers_url": "https://api.github.com/users/satbai/followers",

        "following_url": "https://api.github.com/users/satbai/following{/other_user}",

        "gists_url": "https://api.github.com/users/satbai/gists{/gist_id}",

        "starred_url": "https://api.github.com/users/satbai/starred{/owner}{/repo}",

        "subscriptions_url": "https://api.github.com/users/satbai/subscriptions",

        "organizations_url": "https://api.github.com/users/satbai/orgs",

        "repos_url": "https://api.github.com/users/satbai/repos",

        "events_url": "https://api.github.com/users/satbai/events{/privacy}",

        "received_events_url": "https://api.github.com/users/satbai/received_events",

        "type": "User",

        "site_admin": false

      },

      "content_type": "application/x-gzip",

      "state": "uploaded",

      "size": 3157816,

      "download_count": 2124,

      "created_at": "2019-03-12T21:18:06Z",

      "updated_at": "2019-03-12T21:18:07Z",

      "browser_download_url": "https://github.com/Microsoft/artifacts-credprovider/releases/download/0.1.15/Microsoft.NuGet.CredentialProvider.tar.gz"

    },

    {

      "url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/releases/assets/11496505",

      "id": 11496505,

      "node_id": "MDEyOlJlbGVhc2VBc3NldDExNDk2NTA1",

      "name": "Microsoft.NuGet.CredentialProvider.zip",

      "label": null,

      "uploader": {

        "login": "satbai",

        "id": 24945574,

        "node_id": "MDQ6VXNlcjI0OTQ1NTc0",

        "avatar_url": "https://avatars0.githubusercontent.com/u/24945574?v=4",

        "gravatar_id": "",

        "url": "https://api.github.com/users/satbai",

        "html_url": "https://github.com/satbai",

        "followers_url": "https://api.github.com/users/satbai/followers",

        "following_url": "https://api.github.com/users/satbai/following{/other_user}",

        "gists_url": "https://api.github.com/users/satbai/gists{/gist_id}",

        "starred_url": "https://api.github.com/users/satbai/starred{/owner}{/repo}",

        "subscriptions_url": "https://api.github.com/users/satbai/subscriptions",

        "organizations_url": "https://api.github.com/users/satbai/orgs",

        "repos_url": "https://api.github.com/users/satbai/repos",

        "events_url": "https://api.github.com/users/satbai/events{/privacy}",

        "received_events_url": "https://api.github.com/users/satbai/received_events",

        "type": "User",

        "site_admin": false

      },

      "content_type": "application/x-zip-compressed",

      "state": "uploaded",

      "size": 3949510,

      "download_count": 15441,

      "created_at": "2019-03-12T21:18:02Z",

      "updated_at": "2019-03-12T21:18:03Z",

      "browser_download_url": "https://github.com/Microsoft/artifacts-credprovider/releases/download/0.1.15/Microsoft.NuGet.CredentialProvider.zip"

    }

  ],

  "tarball_url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/tarball/0.1.15",

  "zipball_url": "https://api.github.com/repos/Microsoft/artifacts-credprovider/zipball/0.1.15",

  "body": "- Fixing 'task is canceled' issue\r\n- Adding mutex handling to SessionTokenCache\r\n- Adding more verbose logs"

}

nuget commandline verbosity not matched causes random crashes

Using current version along nuget.exe causes random crashes when nuget -verbosity parameter is defined. This is due to mismatch of possible values of this parameter. You are using LogLevel from https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Common/Errors/LogLevel.cs

    public enum LogLevel
    {
        Debug = 0,
        Verbose = 1,
        Information = 2,
        Minimal = 3,
        Warning = 4,
        Error = 5
    }

while you should be using Verbosity from https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Clients/NuGet.CommandLine/Common/Verbosity.cs

    public enum Verbosity
    {
        Normal,
        Quiet,
        Detailed
    }

Due to current implementation, every time that verbosity is set as parameter of nuget executable and something odd happens (like authentication not working) app evaluates verbosity argument and crashes like that:

[CredentialProvider] Could not find ADAL token for https://company.pkgs.visualstudio.com/_packaging/company/nuget/v3/index.json
[CredentialProvider] Failed to acquire bearer token for VSTSSessionTokenClient
WARNING: The plugin credential provider could not acquire credentials. Authentication may require manual action. Consider re-running the command with --interactive for `dotnet`, /p:NuGetInteractive="true" for MSBuild or removing the -NonInteractive switch for `NuGet`
WARNING: The credential plugin model used by 'M:\j_ukcamsjenkins02_CFP_PU_x86_9\Build\NuGet\Client\CredentialProvider.Microsoft.exe' is deprecated. Please contact the provider of the plugin for an alternative. More information about the recommended plugin model can be found at 'https://aka.ms/nuget-cross-platform-authentication-plugin'.
CredentialProvider.Microsoft: Unhandled Exception: PowerArgs.ValidationArgException: detailed is not a valid value for type LogLevel, options are Debug, Verbose, Information, Minimal, Warning, Error
CredentialProvider.Microsoft: at PowerArgs.ArgRevivers.ReviveEnum(Type t, String value, Boolean ignoreCase)
CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.Revive(String commandLineValue)
CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.Populate(HookContext context)
CredentialProvider.Microsoft: at PowerArgs.CommandLineArgument.PopulateArguments(List`1 arguments, HookContext context)
CredentialProvider.Microsoft: at PowerArgs.Args.ParseInternal(CommandLineArgumentsDefinition definition, String[] input)
CredentialProvider.Microsoft: at PowerArgs.Args.<>c__DisplayClass13_0.<ParseAction>b__0()
CredentialProvider.Microsoft: at PowerArgs.Args.Execute[T](Func`1 argsProcessingCode)
CredentialProvider.Microsoft: at PowerArgs.Args.ParseAction(CommandLineArgumentsDefinition definition, String[] args)
CredentialProvider.Microsoft: at PowerArgs.Args.ParseAction(Type t, String[] args)
CredentialProvider.Microsoft: at PowerArgs.Args.Parse(Type t, String[] args)
CredentialProvider.Microsoft: at PowerArgs.Args.Parse[T](String[] args)
CredentialProvider.Microsoft: at PowerArgs.Args.<>c__DisplayClass22_0`1.<ParseAsync>b__0()
CredentialProvider.Microsoft: at System.Threading.Tasks.Task`1.InnerInvoke()
CredentialProvider.Microsoft: at System.Threading.Tasks.Task.Execute()
CredentialProvider.Microsoft: --- End of stack trace from previous location where exception was thrown ---
CredentialProvider.Microsoft: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
CredentialProvider.Microsoft: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
CredentialProvider.Microsoft: at NuGetCredentialProvider.Program.<Main>d__11.MoveNext() in E:\A\_work\857\s\CredentialProvider.Microsoft\Program.cs:line 63
CredentialProvider.Microsoft: --- End of stack trace from previous location where exception was thrown ---
CredentialProvider.Microsoft: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
CredentialProvider.Microsoft: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
CredentialProvider.Microsoft: at NuGetCredentialProvider.Program.<Main>(String[] args)
Unable to load the service index for source https://company.pkgs.visualstudio.com/_packaging/company/nuget/v3/index.json.
 Response status code does not indicate success: 401 (Unauthorized).
System.InvalidOperationException: Unable to load the service index for source https://company.pkgs.visualstudio.com/_packaging/company/nuget/v3/index.json. 
---> NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source https://company.pkgs.visualstudio.com/_packaging/company/nuget/v3/index.json. 
---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
 at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
 at NuGet.Protocol.HttpSource.<>c__DisplayClass14_0`1.<<GetAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
 at NuGet.Common.ConcurrencyUtilities.<ExecuteWithFileLockedAsync>d__2`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
 ...

Self-hosted build agent and dotnet restore

How are we supposed to configure this if a self-hosted agent is installed on a own server and a build script calls dotnet restore? I have a custom nuget.config that clears and adds:

1 - a Azure DevOps Artifacts feed
2 - NuGet org

Is it supposed to work if I:

Add environment variable: NUGET_PLUGIN_PATHS pointing to folder with the ZIPs plugins

Add environment variable: VSS_NUGET_EXTERNAL_FEED_ENDPOINTS with JSON

{"endpointCredentials": [{"endpoint":"https://myfeed.com/index.json", "username":"not-required", "password":"accesstoken"}]}

The access token has full rights to Packages feeds.

In box cred provider is very old

The version of the cred provider that is in current Visual Studio 2019 previews is 0.1.5 from September 2018. There have been a lot of improvements around Windows auth since then but I'm having to tell people to manually install the latest version. Will you be updating the version that ships with Visual Studio soon?

How to set VSS_NUGET_EXTERNAL_FEED_ENDPOINTS in Azure pipeline?

Hello
I'm not sure if this belongs to this repository.
I set up an Azure DevOps Pipeline and tried to get nugets from telerik feed with auth, but this doesn't work with credential provider (as described here https://docs.microsoft.com/en-us/azure/devops/artifacts/nuget/dotnet-exe)
My Pipeline:

steps:
- task: NuGetToolInstaller@0
  displayName: 'Use NuGet 4.8.1'
  inputs:
    versionSpec: 4.8.1
    checkLatest: true

- task: NuGetCommand@2
  displayName: 'NuGet restore'
  inputs:
    restoreSolution: '$(Parameters.solution)'
    feedsToUse: config
    nugetConfigPath: src/SomeObscureWeb/NuGet.Config

I tried specifying json in VSS_NUGET_EXTERNAL_FEED_ENDPOINTS as Pipeline Variable but it doesn't seem that credential provider in pipline is using this value.

My VSS_NUGET_EXTERNAL_FEED_ENDPOINTS looks like this

{"endpointCredentials": [{
"endpoint":"https://nuget.telerik.com/nuget", 
"username":"[email protected]", 
"password":"xxx"}]}

How should I setup VSS_NUGET_EXTERNAL_FEED_ENDPOINTS for Azure Pipline to add new feed with credentials?

Thank you
Peter

Work with MFA

Is this tool supposed to work if my account has 2 factor authentication turned on? I'm getting prompted for my username and password but am receiving a Response status code does not indicate success: 401 (Unauthorized). I've double checked my credentials so I was wondering if MFA might be giving me issues? I've tried giving it a PAT also with no luck

installcredprovider.ps1 should be digitally signed

When I try to run the powershell script, I get the error:
"installcredprovider.ps1 cannot be loaded. The file C:\Program Files\artifacts-credprovider-master\helpers\installcredprovider.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and settingexecution policy, see about_Execution_Policies at blah blah."

Digitally signing the script will also help protect the integrity of the file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.