按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
我是自己生成的token和自己加中间件实现验证的.暂时不会用identity自带的那一套.
我记得好像是要架identityserver吧?
我用照dudu的文章,,在ms默认的项目上已经测试成功了,,但我现在的项目是,autofac owin webform mvc webapi 集成的,webapi怎么都登录不了,哎,园豆也没了
ConfigureAuth(app, iocBuilder.ServiceProvider);
//这一行代码必须放在ConfiureOAuth(app)之后 ,就这一点,花我两天+一个通宵啊
//app.UseWebApi(config);
结题政策有问题啊,结错题,应该不结的, 结题政策有问题啊,结错题,应该不结的
webapi集成owin使用Oauth认证时能获取accee_token仍无法登录的解决办法