Depuis 1 jour, j'essaye de configurer l'authentification basée sur le token pour mon projet basé sur api. Utiliser le lien ci-dessous comme point de départ.comment configurer l'authentification Owin dans ASP.Net avec succès?
http://www.c-sharpcorner.com/UploadFile/736ca4/token-based-authentication-in-web-api-2/
Mais je suis un peu confus & obtenir des erreurs.
Startup.cs (Situé dans le projet de bibliothèque de classe)
public class Startup
{
public void Configuration(IAppBuilder app)
{
var oauthProvider = new OAuthAuthorizationServerProvider
{
OnGrantResourceOwnerCredentials = async context =>
{
var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
claimsIdentity.AddClaim(new Claim("user", context.UserName));
context.Validated(claimsIdentity);
return;
//context.Rejected();
},
OnValidateClientAuthentication = async context =>
{
string clientId;
string clientSecret;
if(context.TryGetBasicCredentials(out clientId, out clientSecret))
{
if(clientId == context.ClientId && clientSecret == "secretKey")
{
context.Validated();
}
}
}
};
var oauthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/accesstoken"),
Provider = oauthProvider,
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3),
SystemClock = new SystemClock()
};
app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
}
Controller API
[AcceptVerbs("POST")]
[HttpPost]
public string Post([FromBody]User user)
{
if(user.Username == "chetan" && user.Password == "pwd")
{
HttpClient client = new HttpClient();
OAuth.InitOAuth(client, user.Username, user.Password);
return "Success!!User valid for token";
}
else
{
return "Error!! User invalid";
}
}
Ma classe OAuth
public class OAuth
{
public static void InitOAuth(HttpClient client, string userName, string password)
{
string baseAddress = "http://localhost:9000/";
// GETTING THE ERROR AT THIS LINE
using (WebApp.Start<Startup>(url: baseAddress))
{
var form = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", userName },
{"password", password},
};
var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;
var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
}
}
}
Erreur: -
Could not load file or assembly 'Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Sur googler je suis arrivé quelques liens & installé le package suivant: -
Install-package Microsoft.Owin.Host.HttpListener
Web.Config
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="Secretkey" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
Ce que je suis absent ici?
Toute aide ou suggestion très appréciée. Merci.
Pas en ce qui concerne votre problème, mais vous devez d'abord corriger cette horrible mise en œuvre. Votre 'OAuth.InitOAuth' est appelé à partir d'un contrôleur et lance une nouvelle WebApp ?? Je pense que votre flux d'applications est défectueux au moins. –
@ PeterBons, Merci de mettre en évidence. Je suis nouveau à cela, pouvez-vous s'il vous plaît ajouter des détails comment le corriger –
Suivez cette mise en œuvre étape par étape http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api- 2-owin-asp-net-identity/ –