Click here to Skip to main content
14,239,046 members
Rate this:
Please Sign up or sign in to vote.
I am trying to implement custom token based authentication and authorization in angular JS and ASP.NET Web Api.

I have the following log in method, which will check for user details in database and if user exists it generates a token and adds it into the response headers. But I am not able to access the Token header in angular JS call back method. Can anybody let me know how to access this token from angular application?

What I have tried:

[HttpPost]
        [Route("api/login")]
        public IHttpActionResult Authenticate([FromBody]LoginModel credentials)
        {
            IHttpActionResult result;
            HttpResponseMessage response;
            TokenModel tokenInfo;
            var userId = (from n in _data.Users
                          where n.id == credentials.id && n.Password == credentials.Password
                          select n.id).FirstOrDefault().ToString();

            if (!string.IsNullOrEmpty(userId))
            {
                tokenInfo = tokenFunctions.GenerateToken(userId);
                if (tokenInfo != null)
                {
                    response = Request.CreateResponse(HttpStatusCode.OK, userId);
                    response.Headers.Add("Token", tokenInfo.AuthToken);
                    response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
                    response.Headers.Add("Access-Control-Expose-Headers", "Token");
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.Unauthorized);
                }

                result = ResponseMessage(response);
                return result;
            }

            return Unauthorized();
        }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100