zoukankan      html  css  js  c++  java
  • 基于IdentityServer4的单点登录——Client

    以MvcClient项目为例

    1.新建项目并添加引用

    新建一个asp .net core 2.0的项目
    引用IdentityModel

    2.配置

    比之前的控制台客户端多这个步骤,需要配置这个客户端的ClientId,Secret,Scheme,作用范围等等,这些内容与IdentityServer的Client的内容对应

    public void ConfigureServices(IServiceCollection services)
    {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    
        services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                //IdentityServer服务器
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                //这个客户端的Id,Secret
                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";
    
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                //这个客户端的范围集合
                options.Scope.Add("api1");
                options.Scope.Add("offline_access");
            });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
    }
    

    3.登录:跳转到IdentityServer的统一登录页面

    因为Authorize特性,访问Secure页面的时候,如果没有登录,会自动跳转到设置的Authority的网址

    [Authorize]
    public IActionResult Secure()
    {
        ViewData["Message"] = "Secure page.";
    
        return View();
    }
    

    4.登陆成功后,调用Api接口

    (1)使用用户令牌访问Api

    var accessToken = await HttpContext.GetTokenAsync("access_token");
    
    var client = new HttpClient();
    client.SetBearerToken(accessToken);
    //访问之前定义好的Api项目的方法
    var content = await client.GetStringAsync("http://localhost:5001/identity");
    

    (2)使用application identity访问Api

    //先访问IdentityServer服务器,获得授权令牌
    //传参访问地址、客户端Id,客户端Secret
    var tokenClient = new TokenClient("http://localhost:5000/connect/token", "mvc", "secret");
    //传参范围
    var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
    
    //根据授权令牌访问Api
    var client = new HttpClient();
    client.SetBearerToken(tokenResponse.AccessToken);
    //访问之前定义好的Api项目的方法
    var content = await client.GetStringAsync("http://localhost:5001/identity");
  • 相关阅读:
    mysql 历史版本下载
    mysql 5.7 版本 You must reset your password using ALTER USER statement before executing this statement报错处理
    5.7 zip 版本的安装 以及遇到的坑
    mysql 5.6zip版本的卸载与5.7 zip 版本的安装
    mysql数据库的备份与还原
    本地Navicat连接docker里的mysql
    docker修改数据库密码
    docker 在push镜像到本地registry出现的500 Internal Server Error
    linux 没有界面内容显示不全解决办法
    json与map互相转换
  • 原文地址:https://www.cnblogs.com/Lulus/p/7986644.html
Copyright © 2011-2022 走看看