我有像这样的API方法
[HttpGet]
public string UpdateComputerDescriptions()
{
var cred = System.Net.CredentialCache.DefaultCredentials;
UpdateDescriptionsAndTimestamp(System.Net.CredentialCache.DefaultNetworkCredentials);
return "done";
}
我试图用PowerShell用
来调用它$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
并且
Invoke-WebRequest $url -Credential $creds
我的问题是我需要将$creds
凭据传递给我的UpdateDescrptionsAndTimestamp
方法。
但是,当我在API方法中检查DefaultCredentials
和DefaultNetworkCredentials
个对象时,它们不包含任何值(我希望至少看到其中的用户名)。
我甚至尝试将签名更改为public string UpdateComputerDescriptions(NetworkCredential credential)
并使用
进行调用Invoke-WebRequest $url -Body @{credential=$creds} -Credential $creds
但我得到的结果相同。
我怎样才能做到这一点?
注意我不想传递纯文本(或者 - 就此而言 - 加密)凭据,因为powershell脚本最终会以用户身份运行,我只会传入默认凭据。我只需要知道如何从API中检索它
答案 0 :(得分:0)
这是我过去的工作(通过Authorization标头传递信息作为Base64编码的字符串:
<强> C#强>
HttpContext httpContext = HttpContext.Current;
string authHeader = httpContext.Request.Headers["Authorization"];
if (authHeader == null || !authHeader.StartsWith("Basic"))
throw new Exception("The authorization header is empty or isn't Basic.");
string encodedCredentials = authHeader.Substring("Basic".Length).Trim();
string credentialPair = Encoding.Unicode.GetString(Convert.FromBase64String(encodedCredentials));
var credentials = credentialPair.Split(new[] { ":" }, StringSplitOptions.None);
var username = credentials[0];
var password = credentials[1];
<强> Powershell的强>
$username = "username"
$password = "password"
$url = "yourUrl"
$credentials = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($username + ":" + $password))
Invoke-WebRequest -Uri $url -Headers @{Authorization = "Basic $credentials"}
但是,您可能最好为基于令牌的身份验证创建系统(see link here)
编辑进一步解释
深入研究C#控制器的一个例子:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Http;
namespace Application.Controllers
{
public class GetDataController : ApiController
{
public IEnumerable<string> Get()
{
var user = AuthUser(HttpContext.Current);
var dataset = new List<string>();
// code to populate dataset
return dataset;
}
//** I would put this somewhere else in your application so you can reuse it **\\
private static User AuthUser(HttpContext httpContext)
{
var authHeader = httpContext.Request.Headers["Authorization"];
if (authHeader == null || !authHeader.StartsWith("Basic"))
throw new Exception("The authorization header is empty or isn't Basic.");
var encodedCredentials = authHeader.Substring("Basic".Length).Trim();
var credentialPair = System.Text.Encoding.Unicode.GetString(Convert.FromBase64String(encodedCredentials));
var credentials = credentialPair.Split(new[] {":"}, StringSplitOptions.None);
var username = credentials[0];
var password = credentials[1];
var user = new User();
// code to validate login & populate user model
return user;
}
}
}
您可能需要安装WebApi软件包。
在Nuget软件包管理器控制台中:Install-Package Microsoft.AspNet.WebApi