简体   繁体   中英

how to set up Owin Authentication in ASP.Net successfully?

For last 1 day, I am trying to set up Token Based Authentication for my api based project.

Using the below link as start point.
http://www.c-sharpcorner.com/UploadFile/736ca4/token-based-authentication-in-web-api-2/

But I am bit confused & getting errors.

Startup.cs (Located in Class library project)

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);  
    }
}

API Controller

[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";
        }
    }

My OAuth class

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);

        }
    }
}

Error:-

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)

On Googling I got couple of links & installed the following package:-

 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>

What I am missing here?

Any help or suggestion highly appreciated. Thanks.

Maybe problem is:

publicKeyToken="Secretkey" 

You have try to change:

<dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM