좋아, 감사 @Pinpoint을 올바른 방향으로 나를 가리키는 위해.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddOpenIddict<ApplicationUser, ApplicationRole, ApplicationDbContext>()
.DisableHttpsRequirement()
.EnableTokenEndpoint("/connect/token")
.AllowPasswordFlow()
.AllowRefreshTokenFlow()
.UseJsonWebTokens();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseOpenIddict();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,
Audience = "http://localhost:24624/",
Authority = "http://localhost:24624/"
});
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ApplicationDbContext :
그러나 여기 내 Startup.cs 구성입니다.CS :
public class ApplicationDbContext : OpenIddictDbContext<ApplicationUser, ApplicationRole>
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
ApplicationRole.cs :
public class ApplicationRole : IdentityRole
{
}
ApplicationUser.cs :
public class ApplicationUser : OpenIddictUser
{
}
ServiceController.cs :
[Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]
[Route("api/service")]
public class ServiceController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public ServiceController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpGet]
[Route("getdata")]
public async Task<IActionResult> GetData()
{
var user = await _userManager.GetUserAsync(User);
if (user == null) return Ok("No user/not logged in");// if Authorize is not applied
return Ok(user);
}
}
여기에 키가 ServiceController입니다. cs : [Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]
@Pinpoint : 302를 반환하고 계정/로그인으로 리디렉션했기 때문에 app.UseOAuthValidation()을 사용하지 않았습니다.
그래서 지금은 다음과 같이 작동
- 에 액세스하는 http://domain.com, 사용자 등, 데이터를 확인, 로그인, 등록 할 수 있습니다
- 사용자, 모바일 앱을 다운로드 등록, 로그인 및 데이터를 얻을 수
api 측에서 사용자 등록 로그인을 구현하는 것은 쉽고 간단합니다.
피들러를 사용하고 http://domain.com/api/service/getdata에 GET을 발행하면 302가 반환되고 계정/로그인으로 리디렉션되는 것이 문제였습니다. app.UseIdentity()를 제거하면 401 Unauthorized가 반환되지만 사용자는 UI http://domain.com을 사용하여 더 이상 로그인 할 수 없었을 것입니다. 이 [Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]
을 ServiceController에 추가하면 문제가 해결됩니다.
@Pinpoint app.UseOAuthValidation()의 이점은 무엇입니까?
이 답변을 확인하십시오. http://stackoverflow.com/questions/41551430/asp-net-core-no-redirect-on-api-auth-error/41551965#41551965, app.MapWhen을 사용하는 것은 다른 방법입니다. 당신은 할 필요가 없습니다 [Authorize (ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)] –
"ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme"을 기본값으로 만들 수 있는지 궁금합니다. 그래서 모든 컨트롤러에이를 설정하지 않아도됩니다. –