MVC Web-API - token based authentication

Giganews Newsgroups
Subject: MVC Web-API - token based authentication
Posted by:  Miss (misbah.ali7…@gmail.com)
Date: Thu, 27 Nov 2014

I am writing to seek help, as to create a token based authentication. I am =
little unsure, how the token is created for each user? Is the token string =
generated when the user logs in or initially all the users should have a to=
ken value stored with them in the database.=20
=20
Is it possible to pass the token using Delegating Handler?

-------------------------------------------------------------------------
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage r=
equest, CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authValue =3D request.Headers.Authori=
zation;
=20
            if (authValue =3D=3D null || authValue.Scheme !=3D BasicAuthRes=
ponseHeaderValue)
            {
                return Unauthorized(request);
            }
=20
            string[] credentials =3D Encoding.ASCII.GetString(Convert.FromB=
ase64String(authValue.Parameter)).Split(new[] { ':' });
            if (credentials.Length !=3D 2 || string.IsNullOrEmpty(credentia=
ls[0]) || string.IsNullOrEmpty(credentials[1]))
            {
                //return Unauthorized(request);
                var resp =3D new HttpResponseMessage(HttpStatusCode.Unautho=
rized)
                {
                    Content =3D new StringContent(string.Format("access den=
ied")),
                };
            }
=20
            api_login user =3D repository.Validate2(credentials[0], credent=
ials[1]);
                if (user =3D=3D null)
            {
                var resp =3D new HttpResponseMessage(HttpStatusCode.Unautho=
rized)
                {
                    Content =3D new StringContent(string.Format("access den=
ied")),
                };
                return Unauthorized(request);              =20
            }
            else
            {
                var roles =3D repository.GetRolesForUser(user.username);
                IPrincipal principal =3D new GenericPrincipal(new GenericId=
entity(user.username, BasicAuthResponseHeaderValue), roles);
                Thread.CurrentPrincipal =3D principal;
                HttpContext.Current.User =3D principal;
            }
=20
            return base.SendAsync(request, cancellationToken);
=20
        }

------------------------------------------------------------------------

if anyone, could explain the process/steps involved, for building this toke=
n, it would be very much appreciated.=20
Any further help would be very much appreciated. Thank you

Replies