Web API 已拒绝为此请求授权

2021-07-04 19:07

阅读:511

标签:orm   tor   view   ajax   https   ready   word   turn   overview   

原理

技术分享图片

1、注册账号 http://localhost:59345/api/Account/Register

{
"Email": "XXX@qq.com",
"Password": "***",
"ConfirmPassword": "***"
}

 

2、获取Token http://localhost:59345/Token

Content-Type:application/x-www-form-urlencoded  

grant_type:password

username:XXX@qq.com

password:***

工具

技术分享图片

 

代码

private string GetToken(string host)
{

        var client = new RestClient(host);

        var request = new RestRequest("/token", Method.POST);

        request.AddParameter("grant_type", "password");

        request.AddParameter("userName", "用户名");

        request.AddParameter("password", "密码");

        //request.AddHeader("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)));

        var response = client.Execute(request);

        var s = JObject.Parse(response.Content)["access_token"].Valuestring>();

        return s;

}

 3、传入Token

// If we already have a bearer token, set the Authorization header.
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
    headers.Authorization = Bearer  + token;
}

$.ajax({
    type: GET,
    url: api/values/1,
    headers: headers
}).done(function (data) {
    self.result(data);
}).fail(showError);

 

参考资料:

http://www.codes51.com/itwd/3700437.html

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

 

Web API 已拒绝为此请求授权

标签:orm   tor   view   ajax   https   ready   word   turn   overview   

原文地址:https://www.cnblogs.com/chengNet/p/9842273.html


评论


亲,登录后才可以留言!