2017-08-13 82 views
1

已经挖了3天,仍然无法找到一个好的答案。真的很感谢,如果有人可以帮助我 例如。客户端使用登录功能从www.client.com到 我的web api验证成功并向用户发送令牌。客户如何使用令牌API返回与Web api如何使用从API发送的令牌

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

客户端脚本

function login() { 
    $.ajax({ 
     url: 'http://www.azapi.com:81/token', 
     contenttype: 'application/json', 
     data: { username: '[email protected]', password: '[email protected]', 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') 
     } 

    }) 
} 

属性的方法来访问的方法。客户端呼吁从跨域全光照阿贾克斯的方法和我的WebAPI已经在web.config中

回答

0

打开的WebAPI配置和CRO公司政策的CRO当他们送他们应该添加一个名为“授权”与头值的请求你的令牌。

然后,当请求到来时,你可以拉出来的标题和工艺验证控制

+0

我在方法本身拉头?意味着我的方法应该有一个头/ URL的参数?但不允许访问该方法,因为它不是授权的 –

+0

不,您将标头置于REQUEST中。该请求应该添加标题。每当请求到达时你都要检查标题。这可以通过全局(基本)ApiController或通过FilterAttribute来实现。 – HGMamaci

+0

如果我加入了令牌到的HttpOnly的cookie,你知道我怎么能读取和设置令牌服务器端后,我将请求发送 – DevEng

0

你应该写一个自定义AuthorizationAttribute这样的:

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; 
     } 
    } 
} 
+0

我复制的代码,它显示错误说域服务没有被发现。我更改为我的名字空间,但显示相同的错误。 –

+0

看到这一点: https://stackoverflow.com/questions/43201580/custom-authorize-attribute-in-web-api – Mahdi

0

一旦用户通过验证后,他可以送

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

       } 
      } 
     } 
    } 
+0

我不能重写此方法。它没有被发现在授权属性 –

+0

我已经更新了我原来的帖子。在控制器上使用文件管理器。 [AuthorizeFilter] 公共的ActionResult指数() { 返回查看(); } 让我知道它是否有效。 – Imran

0

:在请求头令牌,您可以在Authorize过滤一些类似下面的代码检查请求头试试这个:使用这个作为你的控制器方法上的过滤器

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

} 
相关问题