locked
Help Needed in API authntication RRS feed

  • Question

  • User1489758560 posted

    Version : asp.net 4.5 Web API2

    Hi,

    I am creating web API2 to be used by users.

    I need to validate the user against my database. So i thought of going with basic authentication. Is it good idea? if you have any workable sample please share it with me. It will be useful for everyone who reads this post. or any sample url which explains about implementing that

    Thanks

    Wednesday, April 29, 2015 7:51 AM

Answers

  • User-782957977 posted

    Visual Studio helps you to implement token based authentication. Please do following steps

    1) Please create a new Asp.net Web Api project by selecting Web Api project template in Visual Studio.
     Click change authentication button , then select Individual Account Authentication radio button from template selection window.
    2) Now Visual Studio will add required Authentication code using OWIN middleware
    3) Please call Register Action method in Account controller for adding users in AspNetUsers table. Asp.Net identity uses AspNetUsers table for keeping user information's
    4) When user first access web api, call Token handler with user name and password. JQuery code to call token handler to get token is included in following link
     http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api.

    You can also refer following links

    http://typecastexception.com/post/2014/10/26/ASPNET-Web-Api-and-Identity-20-Customizing-Identity-Models-and-Implementing-Role-Based-Authorization.aspx

    http://forums.asp.net/t/2037968.aspx?UI+for+Login+and+Registration

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 29, 2015 8:30 PM
  • User-782957977 posted

    Please put a break point in Web Api authentication code which returns "invalid_grant" error message and see the issue ( When  project is created with web api project template, this code is in ApplicationOAuthProvider.cs).

    Also try following code to access auth token

    HttpClient client = new HttpClient();
                var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", "microsoft@gmail.com"), 
                            new KeyValuePair<string, string> ( "Password", "password")                    };
                var content = new FormUrlEncodedContent(pairs);
                // Attempt to get a token from the token endpoint of the Web Api host:
                HttpResponseMessage response = client.PostAsync("http://localhost:47503/token",content).Result;
                var result = response.Content.ReadAsStringAsync().Result;



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 3, 2015 9:15 PM

All replies

  • User-782957977 posted

    You can use basic authentication. Please see following links for basic authentication

    http://weblog.west-wind.com/posts/2013/Apr/18/A-WebAPI-Basic-Authentication-Authorization-Filter

    http://www.asp.net/web-api/overview/security/authentication-filters

    In case of basic authentication, you need to pass user name/password as clear text along with each request. If you use Asp.net Web Api individual account authentication, you can avoid this. You can pass user name/password along with first request to get Authentication token and in sub sequent request you need to pass only authentication token.

    http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    Wednesday, April 29, 2015 9:10 AM
  • User1489758560 posted

    Hi Santhosh. 

    Thanks for your reply. When i was trying got find the authentication mechanism i found few ways for individual account,

    Basic Authentication

    Token based authentication 

    I am sure the token based authentication is the best choice.but am not sure where to start from.  Here are my understanding about the token based authentication.

     1.  API  to to get authorization from authorization server  and token will be created and sent to API

    2.  API will server controller based on authorized token

    Please connect me if am wrong. also to achieve this token based authentication, from the internet i came to know that  OWIN has to be used as middleware to achieve the token based concept.

    I am really struggled who to implement this OWIN. I followed this article. but it doesn't have full implementation logic. Any suggestion please how to implement

    http://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection

    Wednesday, April 29, 2015 9:48 AM
  • User-782957977 posted

    Visual Studio helps you to implement token based authentication. Please do following steps

    1) Please create a new Asp.net Web Api project by selecting Web Api project template in Visual Studio.
     Click change authentication button , then select Individual Account Authentication radio button from template selection window.
    2) Now Visual Studio will add required Authentication code using OWIN middleware
    3) Please call Register Action method in Account controller for adding users in AspNetUsers table. Asp.Net identity uses AspNetUsers table for keeping user information's
    4) When user first access web api, call Token handler with user name and password. JQuery code to call token handler to get token is included in following link
     http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api.

    You can also refer following links

    http://typecastexception.com/post/2014/10/26/ASPNET-Web-Api-and-Identity-20-Customizing-Identity-Models-and-Implementing-Role-Based-Authorization.aspx

    http://forums.asp.net/t/2037968.aspx?UI+for+Login+and+Registration

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 29, 2015 8:30 PM
  • User1489758560 posted

    Hi Santhosh,

    thanks for your reply. I am using visual studio 2013. I already created Asp.net web API application using "Asp.net Empty Webapplication" template and created required controllers for my project. So now my turn is to create authentication. From your explanation should  i need to create another API application? In the VS 2013 , when i choose the MVC4 then only it shows WEB API.  My requirement, i don't want to create MVC application. Just Web API. AS you suggested, the option individual account will only prompt if i choose MVC4->WebAPI.  How do i go from here? any suggestion please.

    Wednesday, April 29, 2015 10:07 PM
  • User-782957977 posted

    Individual Account Authentication option will not be available if you start with Asp.net Empty Webapplication. You need to create project with Asp.Net Web Api project template.

    In case of empty project, please refer following link

    http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

    Thursday, April 30, 2015 11:44 PM
  • User1489758560 posted

    Hi Santhosh,

    Thanks, as a first step i would like to play with basic authentication. once i am confident, i will work on taken based. could you please help on the below post

    http://forums.asp.net/t/2048223.aspx?Help+Needed+in+Basic+Authencation

    Friday, May 1, 2015 7:12 AM
  • User1489758560 posted

    Hi Santhosh,

    I have learned about bearer token authentication using the below link,

    https://www.youtube.com/watch?v=jF38zIiX4uE

    public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
                app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
                {
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    Provider = new OAuthAuthorizationServerProvider()
                    {
                        OnValidateClientAuthentication = async c =>
                            {
                                c.Validated();
                            },
                        OnGrantResourceOwnerCredentials = async c =>
                            {
                                if (c.UserName == "microsoft@gmail.com" && c.Password == "password")
                                {
                                    ClaimsIdentity id = new ClaimsIdentity(
                                        new Claim[] { new Claim(ClaimTypes.Name, c.UserName) },
                                        OAuthDefaults.AuthenticationType);
                                    c.Validated();
                                }
                            }
                    }
                }
                );
            }
        }

    When i try to get token i am getting message as invalid grant

    http://localhost:47503/token

    grant_type=password&username=microsoft@gmail.com&password=password

    method : POST

    browser : chrome

    not sure why it throws this error, Checked in fiddler and getting "error=invalid_grant"

    even i tried including the content type as 

    Content-Type: application/x-www-form-urlencoded

    but no hope.

    Any suggestion please

    Sunday, May 3, 2015 1:02 AM
  • User-782957977 posted

    Please put a break point in Web Api authentication code which returns "invalid_grant" error message and see the issue ( When  project is created with web api project template, this code is in ApplicationOAuthProvider.cs).

    Also try following code to access auth token

    HttpClient client = new HttpClient();
                var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "username", "microsoft@gmail.com"), 
                            new KeyValuePair<string, string> ( "Password", "password")                    };
                var content = new FormUrlEncodedContent(pairs);
                // Attempt to get a token from the token endpoint of the Web Api host:
                HttpResponseMessage response = client.PostAsync("http://localhost:47503/token",content).Result;
                var result = response.Content.ReadAsStringAsync().Result;



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 3, 2015 9:15 PM
  • User1489758560 posted

    Hi Santhosh,

    Appreciated your time. I am able to create the bearer token with help of wasson's article and article referred by you.  I played with few samples. please help me on understanding the below points,

    1. I have authorize attribute in the controller level. not method level. would this be correct mechanism?

    2. Once the client gets token, they need to send the token on the POST to get authorized to access the controller and it's methods.

    3.Whoever is calling the API they will get unique token

    4.What are the key points that i need to verify for this token based authentication?

    Monday, May 4, 2015 7:20 AM
  • User-782957977 posted

    1) You can use Authorize attribute in controller level

    2) Client should always include token in each request

    3) Each client will get unique token

    4) Web Api will verify token from client. Always use SSL for Client and server communication

    Monday, May 4, 2015 10:58 PM