簡體   English   中英

使用Openiddict的ASP.NET Core 1.0 OAuth服務器

[英]ASP.NET Core 1.0 OAuth Server using Openiddict

我想使用Openiddict OAuth來保護我的ASP.NET Core 1.0 Web應用程序中的api端點。 api端點將由電話應用程序調用,用戶必須使用用戶名和密碼登錄。

流程如下:

  • 用戶可以通過Web應用程序注冊和登錄: https://www.domain.comhttps://www.domain.com
  • 用戶安裝手機應用程序,他們可以使用手機應用程序登錄和注冊。 登錄,注冊和數據訪問是通過api端點完成的:示例: https://www.domain.com/api/service/getsomedatahttps://www.domain.com/api/service/getsomedata

如何配置Openiddict OAuth,以便使用OAuth保護API端點?

如何配置Openiddict OAuth,以便使用OAuth保護API端點?

您的方案聽起來像是簡單的“資源所有者密碼憑據”授權的良好候選 ,它基本上是OAuth2等效的基本或表單身份驗證。

這是我建議的:

創建一個新的AccountController / RegistrationController API控制器,負責創建新帳戶:

由於此階段不存在用戶帳戶,因此您無法在此處使用令牌身份驗證(就像默認的AccountController.Register模板在注冊用戶之前不需要cookie身份驗證一樣)。

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

使用OAuth2驗證中間件來保護您的API:

要啟用令牌身份驗證,請參閱AspNet.Security.OAuth.Validation 1.0.0-alpha2-final包並在app.UseOAuthValidation()之前添加app.UseMvc() 要使身份驗證成為必需,只需使用[Authorize]屬性,就像使用Cookie身份驗證一樣。

不要猶豫,玩這個樣本 它不會將移動應用程序用於客戶端部分,但您應該很容易理解它是如何工作的。

有關更多信息,您還可以閱讀此博客文章,由Mike Rousos撰寫,用於Microsoft .NET Web開發和工具博客: ASP.NET核心中的承載令牌身份驗證

好的,謝謝@Pinpoint指出我正確的方向。

但是這是我的Startup.cs配置:

   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.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:我沒有使用app.UseOAuthValidation(),因為它返回302並重定向到Account / Login。

所以現在它的工作原理如下:

  • 訪問http://domain.com ,用戶可以注冊,登錄,查看數據等。
  • 用戶可以下載移動應用程序,注冊,登錄和獲取數據

在api端實現用戶注冊登錄非常簡單直接。

問題是使用fiddler並向http://domain.com/api/service/getdata發出GET,返回302並重定向到Account / Login。 如果我刪除了app.UseIdentity(),那么如果將返回401 Unauthorized但是用戶將無法再使用用戶界面http://domain.com登錄。 [Authorize(ActiveAuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]到我的ServiceController解決了這個問題。

@Pinpoint app.UseOAuthValidation()的好處是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM