7

ASP.NET Core 1.0 Webアプリケーションでapiエンドポイントを保護するためにOpeniddict OAuthを使用したいと思います。 apiエンドポイントは電話アプリによって呼び出され、ユーザーはユーザー名とパスワードでログインする必要があります。ASP.NET Core 1.0 OAuthサーバー(Openiddictを使用)

  • ユーザー登録して、Webアプリケーション経由でログインすることができます:https://www.domain.com
  • ユーザーの電話アプリをインストールし、そして彼らは、ログインして携帯電話のアプリを使用して登録することができます

    流れは次のようになります。例:ログイン、登録およびデータアクセスがapiエンドポイントを介して行われるhttps://www.domain.com/api/service/getsomedata

どのように私はOpeniddict OAuthのはそう、私はOAuthのを使用してAPIエンドポイントを保護することができます設定することができますか?

答えて

5

OAuthを使用してAPIエンドポイントを保護するには、どうすればOpeniddict OAuthを設定できますか?

あなたのシナリオはthe simple "resource owner password credentials" grantの候補者のように聞こえます。これは、基本的には基本認証またはフォーム認証のOAuth2に相当します。ここで

は、私がお勧めしたいものだ:ユーザーアカウントは、この段階では存在しないので、あなたは「でき

は、新しいアカウントを作成する責任AccountController/RegistrationController新しいAPIコントローラを作成します。ここでトークン認証を使用しないでください(デフォルトのAccountController.Registerテンプレートは、ユーザーが登録される前にクッキー認証を要求することができないように)。

設定OpenIddictトークンエンドポイントを有効にして、リソースの所有者のパスワードの認証情報を付与できるようにする:

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(); 

は、あなたのAPIを保護するためのOAuth2検証ミドルウェアを使用します。

トークン認証を有効にするには、 AspNet.Security.OAuth.Validation 1.0.0-alpha2-最終パッケージの前にapp.UseOAuthValidation()を加える。認証を必須にするには、Cookie認証の場合のように[Authorize]属性を使用します。

this sampleと一緒に遊ぶことを躊躇しないでください。クライアント側ではモバイルアプリを使用しませんが、どのように動作するのかを簡単に理解する必要があります。

詳細については、あなたはまた、Microsoft .NETのWeb開発ツールのブログのためにマイクRousosによって書かれたこのブログの記事を、読むことができます:Bearer Token Authentication in ASP.NET Core

1

[OK]を、おかげ@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"を作ることが可能かどうか疑問に思っています。 –

関連する問題