简体   繁体   中英

Web api how to use the token send from the api

have been digging this for 3 days and still cant find a good answer to this. Really appreciate if someone can help me out For example . A client use a login function from www.client.com to My web api verified successfully and send a token to a user. How does the client use the token that api return to access a method with

 [RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
    List<customer> list = new List<customer>() { new customer {id=1 ,customerName="Marry",age=13},
        new customer { id = 2, customerName = "John", age = 24 } };
    [Route("GetExployeeByID/{id:long}")]
    [HttpGet]
    [Authorize]
    public customer GetExployeeByID(long id)
    {
        return list.FirstOrDefault(x => x.id == id);
    }
}

client script

   function login() {
    $.ajax({
        url: 'http://www.azapi.com:81/token',
        contenttype: 'application/json',
        data: { username: 'admin@admin.com', password: 'P@ssw0rd', grant_type: 'password' },
        type: 'post',
        crossDomain: true,
        success: function (data) {
            sessionStorage.setItem('token', data.access_token)
        },
        error: function (err) {
            debugger
            alert('error')
        }

    })
}

function getEmployee() {
    $.ajax({
        url: 'http://www.azapi.com:81/api/customer/GetExployeeByID/1',
        datatype: "json",
        type: 'get',
        headers: {
            "access_token": sessionStorage.getItem("token")
        },
        crossDomain: true,
        success: function (data) {
            debugger
            alert(data.customerName)
        },
        error: function (err) {
            debugger
            alert('error')
        }

    })
}

attribute method . The client is calling the method usin Ajax from cross domain and my webapi already open the cros in webapi config and cros policy at web.config

When they send a request they should add a header named "Authorization" with the value of your Token.

Then when the request comes, you can pull it out of the headers and process authentication control

You should write a custom AuthorizationAttribute like this:

public class CheckAttendeeNameAttribute : System.Web.DomainServices.AuthorizationAttribute
{    
    public override bool Authorize(System.Security.Principal.IPrincipal principal)
    {
        if (principal.IsInRole("Attendee") && principal.Identity.Name.StartsWith("A"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Once user is authenticated, he can send the token in request header and you can check for the request header in Authorize Filter something like the following code:

    using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


    namespace WebApplication1.Models
    {
        public class AuthorizeFilter : AuthorizeAttribute
        {
            public bool verifyToken(string token)
            {
                return false;
            }
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {

                // Get the headers
                var headers = httpContext.Request.Headers;
                //your token verification 
                if (verifyToken(headers["SomeHeader"]))
                {
                    return true;
                }
                return false;

            }



            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                try
                {
                    filterContext.Result = new RedirectToRouteResult(new
                    RouteValueDictionary(new { controller = "Home", action = "NotAuthorzied" }));
                }
                catch (Exception ex)
                {

                }
            }
        }
    }

Try this: Use this as a Filter on your Controller method

public class AuthorizationFilter : AuthorizeAttribute
{

            protected override bool IsAuthorized(HttpActionContext actionContext)
            {
                var isAuthenticated = base.IsAuthorized(actionContext);

                if (isAuthenticated)
                {
                     var headers = actionContext.Request.Headers;

                     IEnumerable<string> header;

                     headers.TryGetValues("AuthorizationHeaderName", out header);
                     var token = header.GetEnumerator().Current;

                     //validate your token
                     if (tokenVerification(token))
                     {
                        return true;
                     }

                     return false;
                 }

            }

      private bool tokenVerification (string token)
      {
          if // valid token
           return true;
          else return false;
      }

}

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