IdentityService4的学习

记录下IdentityService4学习

新建两个项目 Identity.Server认证服务,Identity.UserApiService为Api服务,目的来实现通过认证服务认证后才能调用Api服务

在Identity.Server中安装IdentityServer库

创建ApiResource和Client两个资源文件

    public class ApiResourceData {
        /// <summary>
        /// 获取ApiResource
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources() {
            List<ApiResource> list = new List<ApiResource>();
            list.Add(new ApiResource(OAuthConfig.UserApi.ApiName, OAuthConfig.UserApi.ApiName));
            return list;
        }
    }
        public static IEnumerable<Client> GetClients() {
            List<Client> list = new List<Client>();
            list.Add(new Client() {
                ClientId = OAuthConfig.UserApi.ClientId,
                AllowedGrantTypes = new List<string>() {
                    GrantType.ResourceOwnerPassword,//密码模式需要输入用户名和密码
                    GrantType.ClientCredentials,//凭证式
                },
                ClientSecrets = { new Secret(OAuthConfig.UserApi.Secret.Sha256()) },
                AllowedScopes = {OAuthConfig.UserApi.ApiName},
                AccessTokenLifetime=36000

            });
            return list;
        }

在Startup中配置ConfigureServices

            #region 内存模式
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()//默认的开发者证书
                .AddInMemoryApiResources(ApiResourceData.GetApiResources())//IEnumerable的Api资源
                .AddInMemoryClients(ApiClientData.GetClients())
                .AddTestUsers(TestUserData.GetTestUsers());
            #endregion

在Configure中加入

           app.UseIdentityServer();

这样就完成了认证服务了。

我们配置了两种模式,password模式如下

凭证模式如下

这样就可以获取到access_token了,这里要注意传入参数的名称。

接下来在项目Identity.UserApiService中安装IdentityServer4. AccessTokenValidation

在Startup中配置

    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthorization();
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options => {
                    options.Authority = "http://localhost:5000";    //配置Identityserver的授权地址
                    options.RequireHttpsMetadata = false;           //不需要https    
                    options.ApiName = OAuthConfig.UserApi.ApiName;  //api的name,需要和config的名称相同
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();//开启认证
            app.UseMvc();
        }
    }

然后建立一个api控制器并对其加上Authorize特性进行验证

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Authorize]//加上认证
        public IActionResult GetUser(string id) {
            var msg = $"this id is:{id}";
            return Content(msg);
        }
    }

此时我们可以来测试下,在没加token的情况下访问返回的是401错误

我们在headers的Authorization加入token,就能正常返回值了,注意token前需加上"Bearer token"才可以被认证通过

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值