首页 新闻 会员 周边 捐助

.net 3.1使用IdentityServer4,token获取成功,访问接口一直401错误

0
[已关闭问题] 关闭于 2021-12-03 15:57

IdentityServer4

Config

    public static class Config
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            };
        }

        public static IEnumerable<ApiResource> GetApis()
        {
            List<ApiResource> apiResources = new List<ApiResource>();

            string name = "test";

            string displayname = "test";

            ApiResource apiResource = new ApiResource(name, displayname);

            //List<Secret> secrets = new List<Secret>();

            //Secret secret1 = new Secret(EncryptionHelper.Decode("").Sha256());
            //secrets.Add(secret1);

            //apiResource.ApiSecrets = secrets;

            apiResources.Add(apiResource);
            return apiResources;
        }

        public static IEnumerable<Client> GetClients()
        {
            List<Client> clients = new List<Client>();

            //string clientid = JsonHelper.GetParameter(ParameterPath.AuthCorpID);
            //string secret = JsonHelper.GetParameter(ParameterPath.AuthCorpSecret);
            //string clientname = JsonHelper.GetParameter(ParameterPath.AuthCorpName);
            //string name = JsonHelper.GetParameter(ParameterPath.AuthApiReSource);

            string clientid = "test";
            string secret = "test";
            string clientname = "test";
            string name = "test";

            Client client = new Client
            {
                ClientId = clientid,//客户端唯一标识
                ClientName = clientname,//描述
                AccessTokenLifetime = 7200,//设置AccessToken过期时间
            };

            List<string> scopes = new List<string>();
            scopes.Add(name);//可访问资源名称

            client.SlidingRefreshTokenLifetime = 7200;
            client.AbsoluteRefreshTokenLifetime = 2592000;
            client.RefreshTokenExpiration = TokenExpiration.Sliding;
            client.UpdateAccessTokenClaimsOnRefresh = true;
            client.AllowOfflineAccess = true;
            client.RefreshTokenUsage = TokenUsage.ReUse;
            client.AllowedGrantTypes = GrantTypes.ResourceOwnerPassword;
            scopes.Add(StandardScopes.OfflineAccess);
            scopes.Add(StandardScopes.OpenId);
            scopes.Add(StandardScopes.Profile);

            List<Secret> secrets = new List<Secret>();
            Secret secret1 = new Secret(secret.Sha256());//客户端机密—仅与需要机密的流相关
            secrets.Add(secret1);
            client.ClientSecrets = secrets;

            client.AllowedScopes = scopes;
            clients.Add(client);
            return clients;
        }
    }

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.AddControllersWithViews().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);

            // 配置cookie策略
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
            });

            var builder = services.AddIdentityServer()
              .AddInMemoryIdentityResources(Config.GetIdentityResources())
              .AddInMemoryApiResources(Config.GetApis())
              .AddInMemoryClients(Config.GetClients())
              .AddResourceOwnerValidator<LoginValidator>()//用户校验
              .AddProfileService<ProfileService>();//获取用户信息
            //.AddTestUsers(TestUsers.Users);

            builder.Services.AddTransient<IProfileService, ProfileService>();

            builder.AddDeveloperSigningCredential();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCookiePolicy();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            //使用IdentityServer中间件,必须放到 UseRouting 与 UseEndpoints 之间。
            app.UseIdentityServer();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }

API

Startup

    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            //注入同步
            //services.AddHostedService<SyncService>();

            //用户校验
            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            //  .AddIdentityServerAuthentication(options =>
            //  {
            //      options.Authority = JsonHelper.GetParameter(ParameterPath.AuthApiUrl); // IdentityServer服务器地址
            //      options.ApiName = JsonHelper.GetParameter(ParameterPath.AuthApiReSource); // 用于针对进行身份验证的API资源的名称
            //      //options.ApiSecret = ""; //对应ApiResources中的密钥
            //      options.RequireHttpsMetadata = false; // 指定是否为HTTPS
            //  });

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
             .AddIdentityServerAuthentication(options =>
             {
                 options.Authority = "http://127.0.0.1:5001"; // IdentityServer服务器地址
                  options.ApiName = "test"; // 用于针对进行身份验证的API资源的名称
                  options.RequireHttpsMetadata = false; // 指定是否为HTTPS
              });

            //     services.AddAuthentication("Bearer")
            //.AddJwtBearer("Bearer", options =>
            //{
            //    options.Authority = "http://127.0.0.1:5001";
            //    options.RequireHttpsMetadata = false;
            //    options.Audience = "space";
            //});

            #region 配置Swagger
            services.AddSwaggerGen(c =>
            {
                #region 顶部基础信息

                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "WebAPI"
                });
                #endregion

                #region 添加读取注释服务
                //添加对控制器的标签(描述)通过对SwaggerDocTag添加备注
                //c.DocumentFilter<SwaggerDocTag>();
                //var basePath = AppDomain.CurrentDomain.BaseDirectory;

                var basePath = AppContext.BaseDirectory;

                var apiXmlPath = Path.Combine(basePath, "Tencent.Api.xml");
                if (System.IO.File.Exists(apiXmlPath))
                    c.IncludeXmlComments(apiXmlPath, true);//控制器层注释(true表示显示控制器注释)

                var entityXmlPath = Path.Combine(basePath, "Tencent.Model.xml");
                if (System.IO.File.Exists(entityXmlPath))
                    c.IncludeXmlComments(entityXmlPath);//实体类注释
                #endregion

            });
            #endregion

            services.AddMvc(option =>
            {
                option.Filters.Add(new APIResultFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            #region 跨域
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSameDomain", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                    //builder.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
                    ////.AllowCredentials()//指定处理cookie
                //.AllowAnyOrigin(); //允许任何来源的主机访问
                });
            });
            #endregion
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseRouting();

            //跨域
            app.UseCors("AllowSameDomain");

            //使用静态文件
            app.UseStaticFiles();

            app.UseHttpsRedirection();

            //请求错误提示配置
            app.UseErrorHandling();

            //认证
            app.UseAuthentication();

            //授权
            app.UseAuthorization();

            #region 解决Ubuntu Nginx 代理不能获取IP问题
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            #endregion

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors("AllowSameDomain");
            });

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
            });
            #endregion
        }
    }

SpaceController

    /// <summary>
    /// 空间
    /// </summary>
    [Route("api/space/[action]")]
    [EnableCors("AllowSameDomain")]
    [ApiController]
    [Authorize]
    public class SpaceController : ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult judge()
        {
            return Ok("123");
        }
    }
笑叹、的主页 笑叹、 | 初学一级 | 园豆:34
提问于:2021-11-24 17:51
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册