webapi请求头中加了AccessToken但还是返回:{"Message":"已拒绝为此请求授权。"}
2016-07-20 来自:冬虫草~ 2 人回应
按http://www.cnblogs.com/dudu/p/4572752.html在请求头中加了AccessToken

var token = GetAccessToken().Result;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

Console.WriteLine(await(await _httpClient.GetAsync("/api/Hello/1")).Content.ReadAsStringAsync());

 

但成功获取到AccessToken

但还是返回:{"Message":"已拒绝为此请求授权。"}

 

相关代码

public class OauthTest
{
private string clientId = "123456";
private string clientSecret = "abcdef";
private HttpClient _httpClient;
public OauthTest()
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri(Paths.AuthorizationServerBaseAddress);
}

private async Task<string> GetAccessToken()
{
var parameters = new Dictionary<string, string>();
parameters.Add("client_id", clientId);
parameters.Add("client_secret", clientSecret);
parameters.Add("grant_type", "client_credentials");

var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
var responseValue = await response.Content.ReadAsStringAsync();

Console.WriteLine(responseValue);

return JObject.Parse(responseValue)["access_token"].Value<string>();
}
public async Task Test()
{
Console.WriteLine();

var token = GetAccessToken().Result;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

Console.WriteLine(await(await _httpClient.GetAsync("/api/Hello/1")).Content.ReadAsStringAsync());
}
}

 

 public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider中只有

public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
context.TryGetFormCredentials(out clientId, out clientSecret);
//context.TryGetBasicCredentials(out clientId, out clientSecret);

var Id = "123456";
var Secret = "abcdef";
if (clientId == Id && clientSecret == Secret)
{
context.Validated(clientId);
}

return base.ValidateClientAuthentication(context);
}

public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "iOS App"));
var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
context.Validated(ticket);
return base.GrantClientCredentials(context);

//var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
//context.Validated(identity);
//return Task.FromResult(0);
//return base.GrantClientCredentials(context);
}

//园豆好商量,不够可再加,,没了,,就加RMB

 

2016-07-21 来自:abeaver

ConfigureAuth(app, iocBuilder.ServiceProvider);

//这一行代码必须放在ConfiureOAuth(app)之后 ,就这一点,花我两天+一个通宵啊
//app.UseWebApi(config);

2016-07-20 来自:claire

我是自己生成的token和自己加中间件实现验证的.暂时不会用identity自带的那一套.

我记得好像是要架identityserver吧?

您的回应

你还未登陆,不能回应!登陆