Для моего мобильного приложения я пытаюсь создать защищенный API. Я создал oAuth-сервер с Identity Server 3, используя ResourceOwner Flow. Токен успешно сгенерирован. Но всякий раз, когда я вызываю свой защищенный 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 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.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-несанкционированную ошибку.