我正在尝试在 Asp.Net Core ( https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers ) 中实现外部 OAuth。我的应用程序(GitLab)具有回调 URL https://myhost.com/signin-gitlab(中间件默认使用)。
如果我运行下面的代码,我会得到“异常:oauth 状态丢失或无效”。但是,如果我从 Startup.cs 中删除“options.UserInformationEndpoint”,那么我会使用代码和状态参数重定向到 myhost.com/signin-gitlab,中间件应该用它们交换访问令牌。我的问题是,为什么我的状态参数会损坏(使用 UserInformationEndpoint)?为什么我没有获得访问令牌?我在这里想念什么?
我的创业班:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using AspNet.Security.OAuth.GitLab;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MyApp
{
public class Startup
{
private readonly IConfiguration _cfg;
public Startup(IConfiguration configuration) => _cfg = configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddGitLab("Gitlab", options => {
options.ClientId = "...";
options.ClientSecret = "...";
options.AuthorizationEndpoint = "https://mygitlabserver.com/oauth/authorize";
options.TokenEndpoint = "https://mygitlabserver.com/oauth/token";
options.Scope.Clear();
options.Scope.Add("api");
options.SaveTokens = true;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.UserInformationEndpoint = "https://mygitlabserver.com/api/v4/user";
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}
我的控制器:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers
{
public class HomeController : Controller
{
[HttpGet("/")]
public IActionResult Index()
{
return View();
}
[HttpGet("/login")]
public IActionResult LogIn()
{
// Instruct the middleware corresponding to the requested external identity
// provider to redirect the user agent to its own authorization endpoint.
// Note: the authenticationScheme parameter must match the value configured in Startup.cs
return Challenge(new AuthenticationProperties { RedirectUri = "https://myhost.com/signin-gitlab" }, "Gitlab");
}
}
}