码迷,mamicode.com
首页 > Windows程序 > 详细

Web API 已拒绝为此请求授权

时间:2018-10-24 15:55:42      阅读:1193      评论:0      收藏:0      [点我收藏+]

标签: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"].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

 

Web API 已拒绝为此请求授权

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!