来自客户端的web api身份验证

时间:2017-08-11 08:46:53

标签: asp.net-mvc api asp.net-web-api

我有www.api.com和www.client.com 所有注册都将在api.com上完成,登录将在api.com上完成。 client.com只能看到登录表单的UI。

用户登录后,api.com将令牌返回给用户。如何使用令牌访问api.com中的其他webapi?我想访问 val fibonacciValues = hashMapOf<Int, BigInteger>(0 to BigInteger.ONE, 1 to BigInteger.ONE); // * TODO investigate how to do dynamic programming with a pure function ** // private fun calculateFibonacci(n: Int): BigInteger? { if (fibonacciValues.contains(n)) { return fibonacciValues.get(n) } else { val f = calculateFibonacci(n - 2)!!.add(calculateFibonacci(n - 1)) fibonacciValues.put(n, f) return f } } 方法。使用后登录。我将令牌存储在GetExployeeByID

api方法

sessionStorage.setItem('token', data.access_token)

更新1 这是我在登录后调用api的ajax帖子

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

}

2 个答案:

答案 0 :(得分:0)

您应该将请求标头从客户端传递到api

Authorization Basic yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY=

您可以在API中查询标题并提取令牌。

string authorizationHeader = HttpContext.Current.Request.Headers["Authorization"];
string toke =  authorizationHeader.Replace("Bearer ", String.Empty);

我在我的最新项目中所做的是有一个课程AuthToken为我做了很多这样的事情

public class AuthToken : IAuthToken
{
    private string _raw;
    private IDictionary<string, string> _deserialized;

    public string Raw
    {
        get
        {
            if (String.IsNullOrWhiteSpace(_raw))
            {
                string authorizationHeader = HttpContext.Current.Request.Headers["Authorization"];
                _raw =  authorizationHeader.Replace("Bearer ", String.Empty);
            }
            return _raw;
        }
    }

    public IDictionary<string, string> Deserialized
    {
        get
        {
            if (_deserialized == null)
            {
                string[] tokenSplit = Raw.Split('.');
                string payload = tokenSplit[1];
                byte[] payloadBytes = Convert.FromBase64String(payload);
                string payloadDecoded = Encoding.UTF8.GetString(payloadBytes);
                _deserialized =  JsonConvert.DeserializeObject<IDictionary<string, string>>(payloadDecoded);
            }
            return _deserialized;
        }
    } 
}

然后我将其注入UserContext类,我可以将其注入我的控制器等。然后,用户上下文可以根据需要从令牌中提取声明。 (假设是JWT)

public class UserContext : IUserContext
{
    private IList<Claim> _claims;
    private string _identifier;
    private string _email;
    private string _clientId;

    public IAuthToken Token { get; }

    public IList<Claim> Claims
    {
        get
        {
            return _claims ?? (_claims = Token.Deserialized.Select(self => new Claim(self.Key, self.Value)).ToList());
        }
    } 

    public string Identifier => _identifier ?? (_identifier = Token.Deserialized.ContainsKey("sub") ? Token.Deserialized["sub"] : null);

    public string Email => _email ?? (_email = Token.Deserialized.ContainsKey(ClaimTypes.Email) ? Token.Deserialized[ClaimTypes.Email] : null);

    public UserContext(IAuthToken authToken)
    {
        Token = authToken;
    }
}

答案 1 :(得分:0)

您需要将令牌传递给请求标头并调用API网址。可以通过传递您拥有的URL和令牌来调用下面的函数。

static string CallApi(string url, string token) 
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    using (var client = new HttpClient()) 
    {
        if (!string.IsNullOrWhiteSpace(token)) 
        {
            var t = JsonConvert.DeserializeObject<Token>(token);

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
        }
        var response = client.GetAsync(url).Result;
        return response.Content.ReadAsStringAsync().Result;
    }
}

请参阅Token based authentication in Web API以获取详细说明。