7

ASP.NET Core 1.0 웹 응용 프로그램의 API 끝점을 보호하기 위해 Openiddict OAuth를 사용하고 싶습니다. api 엔드 포인트는 전화 앱에서 호출되며 사용자는 사용자 이름과 비밀번호로 로그인해야합니다.Openiddict를 사용하는 ASP.NET 코어 1.0 OAuth 서버

흐름은 다음과 같이 진행됩니다

  • 사용자 등록 및 웹 응용 프로그램을 통해 로그인 할 수 있습니다 : https://www.domain.com
  • 사용자가 전화 응용 프로그램을 설치, 그들은 로그인하여 전화 응용 프로그램을 사용하여 등록 할 수 있습니다. 예 : 로그인, 등록 및 데이터 액세스가 api 엔드 포인트를 통해 이루어집니다 https://www.domain.com/api/service/getsomedata

어떻게 Openiddict OAuth를 그래서 난의 OAuth를 사용하여 API 엔드 포인트를 보호 할 수 있습니다 구성 할 수 있습니다?

답변

5

OAuth를 사용하여 API 끝점을 보호 할 수 있도록 어떻게 Openiddict OAuth를 구성 할 수 있습니까?

시나리오는 기본 또는 양식 인증과 기본적으로 동일한 OAuth2 인 the simple "resource owner password credentials" grant의 좋은 후보로 들립니다.

새 계정 생성의 책임을 새로운 AccountController/RegistrationController API 컨트롤러 만들기 : 사용자 계정이 단계에서 존재하지 않기 때문에

을 수행 할 수 있습니다 '여기

내가 권하고 싶습니다 무엇 여기서 토큰 인증을 사용하지 마십시오 (기본값 AccountController.Register 템플릿은 사용자가 등록되기 전에 쿠키 인증을 요구할 수 없습니다). ,

토큰 인증을 사용하려면 :

services.AddOpenIddict<ApplicationDbContext>() 
    // Disable the HTTPS requirement during development. 
    .DisableHttpsRequirement() 

    // Enable the token endpoint, required to use 
    // the resource owner password credentials grant. 
    .EnableTokenEndpoint("/connect/token") 

    // Enable the password and the refresh token flows. 
    .AllowPasswordFlow() 
    .AllowRefreshTokenFlow(); 

사용

OAuth2를 확인 미들웨어는 API를 보호하기 위해 :

구성 OpenIddict는 리소스 소유자 암호 자격 증명을 부여 토큰 엔드 포인트를 사용하고 수 있도록 참조 AspNet.Security.OAuth.Validation 1.0.0-alpha2- 최종 패키지 앞에 app.UseOAuthValidation()을 추가하십시오. 인증을 필수로 설정하려면 쿠키 인증과 마찬가지로 [Authorize] 속성을 사용하면됩니다.

this sample으로 주저하지 마십시오. 클라이언트 측 부분에는 모바일 앱이 사용되지 않지만 어떻게 작동하는지 쉽게 이해해야합니다.

자세한 내용은, 당신은 또한 마이크로 소프트 .NET 웹 개발 도구 블로그 마이크 Rousos가 쓴이 블로그 게시물을 읽을 수 있습니다 : Bearer Token Authentication in ASP.NET Core

1

좋아, 감사 @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()의 이점은 무엇입니까?

+0

이 답변을 확인하십시오. http://stackoverflow.com/questions/41551430/asp-net-core-no-redirect-on-api-auth-error/41551965#41551965, app.MapWhen을 사용하는 것은 다른 방법입니다. 당신은 할 필요가 없습니다 [Authorize (ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)] –

+0

"ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme"을 기본값으로 만들 수 있는지 궁금합니다. 그래서 모든 컨트롤러에이를 설정하지 않아도됩니다. –

관련 문제