获取401-调用受Identity Server 3保护的.Net Core 2.2 API时出现未经授权的错误

时间:2019-01-04 14:12:47

标签: oauth-2.0 .net-core identityserver3

对于我的移动应用程序,我正在尝试创建一个安全的API。我已经使用ResourceOwner Flow与身份服务器3创建了oAuth服务器。令牌已成功生成。但是,每当我调用受保护的API时,都会收到401未经授权的错误。

OAuth服务器下面的代码

`var defaultmobileClient = new Client
                {

                    ClientId = "iqimplicit",
                    ClientName = "iqimplicit",
                    Flow = Flows.ResourceOwner,
                    AllowAccessToAllScopes = true,
                    IdentityTokenLifetime = 300,//default value is 5 minutes this is the token that allows a user to login should only be used once
                    AccessTokenLifetime = 3600, // default is one hour access token is used for securing routes and access to api in IQ
                    RequireConsent = false,
                    RequireSignOutPrompt = true,
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("mysecret".Sha256())
                    },
                    AllowedScopes = new List<string>
                    {
                        Core.Constants.StandardScopes.OpenId,
                        Core.Constants.StandardScopes.Profile,
                        Core.Constants.StandardScopes.Email,                           
                        Core.Constants.StandardScopes.OfflineAccess
                    },
                    ClientUri = "https://localhost:44300/",                     
                    AccessTokenType = AccessTokenType.Jwt,
                    RedirectUris = new List<string>(),
                    PostLogoutRedirectUris = new List<string>
                    {
                        "https://localhost:44300/"
                    },
                    LogoutSessionRequired = true
                };`

.Netcore api启动看起来如下

`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.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300/ids";
            options.ApiName = "iqimplicit";
            options.ApiSecret = "mysecret";

        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "SGPAY WebApi", Version = "v1" });

        });
        services.Configure<IdentityAppSettings>(Configuration.GetSection("IdentitySettings"));

        services.AddDbContext<SGPAYDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SGPAYDatabase")));
        RegisterDependencies.Register(services);

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "SGPAY WebApi V1");
        });
        app.UseMvc();
    }
}`

控制器如下所示:

`namespace Test
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    // GET: api/Test
    [HttpGet]
    public IActionResult Get()
    {          
        return Ok(new LoginUser {UserName ="Test", Password="User" });
    }

    [Authorize]
    [ValidateAntiForgeryToken]
    // GET: api/Test/5
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id)
    {
        return "value";
    }
}
}`

在致电http://localhost:2305/api/Test时,我应该得到200响应。但是我收到401未经授权的错误。

1 个答案:

答案 0 :(得分:2)

在您的控制器上,不要使用[Authorize]

您将需要在启动时注册承载授权

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

此示例适用于IS4,因此您可能需要对其进行一些微调以满足您的需求。但是最主要的是您需要为控制器注册承载身份验证。