Web API 已拒絕為此請求授權


原理

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"].Value<string>();

        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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM