美文网首页
Identity Server 4 学习(七)访问受认证保护的A

Identity Server 4 学习(七)访问受认证保护的A

作者: 寻找无名的特质 | 来源:发表于2021-11-12 06:15 被阅读0次

我们对前面的客户端稍加改造,使它可以访问受认证保护的客户端。我们先试验使用HttpClient进行后台访问。先在Startup的配置中增加对myapi的访问:

 options.Scope.Add("myapi");

然后创建一个新的页面,修改后台文件的代码如下:

using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json.Linq;

namespace MyClientWebHttps.Pages
{
    public class GetDataJsModel : PageModel
    {
        public string token;
        public string result;
        public async Task OnGet()
        {
            var auth = await HttpContext.AuthenticateAsync();

            var tokens = auth.Properties;
            token = tokens.Items[".Token.access_token"];

            var apiClient = new HttpClient();
            apiClient.SetBearerToken(token);

            var response = await apiClient.GetAsync("http://localhost:5007/WeatherForecast");
            if (!response.IsSuccessStatusCode)
            {
                result=response.StatusCode.ToString();
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                result = content;// JArray.Parse(content);
            }
        }
    }
}

代码很简单,就是取出access_token,并使用这个token访问api资源。访问获得的结果保存在result中。下一步我们研究如何使用ajax访问web api。

相关文章

网友评论

      本文标题:Identity Server 4 学习(七)访问受认证保护的A

      本文链接:https://www.haomeiwen.com/subject/nmyrzltx.html