gpt4 book ai didi

c# - 添加到 dotnetcore 中的 Slack,没有 Identity Framework 错误 : The oauth state was missing or invalid

转载 作者:行者123 更新时间:2023-12-01 16:35:58 25 4
gpt4 key购买 nike

我正在尝试为我的 slackbot 创建一个非常简单的页面,以便用户可以登录和注册。但是,即使使用他们生成的“使用 Slack 登录”按钮,我也会收到错误“oauth 状态丢失或无效。”。 “添加到 Slack”也会发生同样的错误。

我的代码基于 https://dotnetthoughts.net/slack-authentication-with-aspnet-core/ 。尽管它已经过时了,但这是我在网上找到的唯一示例。我尝试找出需要更改哪些内容才能使其与 dotnetcore 3 和 Slack 2.0 配合使用,但我已无计可施。

在我的服务中,在调用AddMvc等之前我有以下内容

services.AddAuthentication(options =>
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "MyAuthCookieName";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.MaxAge = TimeSpan.FromDays(7);
options.ExpireTimeSpan = TimeSpan.FromDays(7);

options.LoginPath = $"/login";
options.LogoutPath = $"/logout";
options.AccessDeniedPath = $"/AccessDenied";
options.SlidingExpiration = true;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
})
//.AddSlack(options =>
//{
// options.ClientId = Configuration["Slack:ClientId"];
// options.ClientSecret = Configuration["Slack:ClientSecret"];
//});
.AddOAuth("Slack", options =>
{
options.ClientId = Configuration["Slack:ClientId"];
options.ClientSecret = Configuration["Slack:ClientSecret"];
options.CallbackPath = new PathString("/signin-slack");
options.AuthorizationEndpoint = $"https://slack.com/oauth/authorize";
options.TokenEndpoint = "https://slack.com/api/oauth.access";
options.UserInformationEndpoint = "https://slack.com/api/users.identity?token=";
options.Scope.Add("identity.basic");
options.Events = new OAuthEvents()
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint + context.AccessToken);
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var userObject = JObject.Parse(await response.Content.ReadAsStringAsync());
var user = userObject.SelectToken("user");
var userId = user.Value<string>("id");

if (!string.IsNullOrEmpty(userId))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}

var fullName = user.Value<string>("name");
if (!string.IsNullOrEmpty(fullName))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Name, fullName, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
}
};
});

我的配置方法看起来像

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.Map("/login", builder =>
{
builder.Run(async context =>
{
await context.ChallengeAsync("Slack", properties: new AuthenticationProperties { RedirectUri = "/" });
});
});

app.Map("/logout", builder =>
{
builder.Run(async context =>
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.Redirect("/");
});
});

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});

除了“oauth 状态无效时丢失”之外,如果在我的应用程序中直接转到/login,我不会收到错误,但我似乎没有以 User 身份登录。 Identity.IsAuthenticated 为 false。

我真的很茫然,需要一些非常感谢的帮助!

谢谢!

大规模更新

我登录到 Slack 后可以正常工作,但无法使用“添加到 Slack”按钮。

这是我的新服务:

services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/logout";
})
.AddSlack(options =>
{
options.ClientId = Configuration["Slack:ClientId"];
options.ClientSecret = Configuration["Slack:ClientSecret"];
options.CallbackPath = $"{SlackAuthenticationDefaults.CallbackPath}?state={Guid.NewGuid():N}";
options.ReturnUrlParameter = new PathString("/");
options.Events = new OAuthEvents()
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, $"{context.Options.UserInformationEndpoint}?token={context.AccessToken}");
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var userObject = JObject.Parse(await response.Content.ReadAsStringAsync());
var user = userObject.SelectToken("user");
var userId = user.Value<string>("id");

if (!string.IsNullOrEmpty(userId))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}

var fullName = user.Value<string>("name");
if (!string.IsNullOrEmpty(fullName))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Name, fullName, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
}
};
});

根据@timur,我抓取了我的 app.Map 并使用了身份验证 Controller :

public class AuthenticationController : Controller
{
[HttpGet("~/login")]
public async Task<IActionResult> SignIn()
{
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "Slack");
}

[HttpGet("~/signin-slack")]
public IActionResult SignInSlack()
{
return RedirectToPage("/Index");
}

[HttpGet("~/logout"), HttpPost("~/logout")]
public IActionResult SignOut()
{
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
CookieAuthenticationDefaults.AuthenticationScheme);
}
}

“添加到 Slack”按钮按原样由 Slack 提供。

<a href="https://slack.com/oauth/authorize?scope=incoming-webhook,commands,bot&client_id=#############"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>

因此,当用户单击“登录”时,它会将他们登录并获取他们的姓名等。您会注意到,在我的身份验证 Controller 中,我添加了一个带有路径“~/signin-slack”的函数,这是因为我手动添加“Options.CallbackPath”以添加状态参数。如果删除“Options.CallbackPath”,我会收到一条错误,指出 oauth 状态丢失或无效。

所以,我不确定 Slack 方面缺少什么。他们让它听起来如此简单!

抱歉,帖子/更新很长。感谢您的帮助。

最佳答案

您提到的同一篇文章下面有一个链接,指向 AspNet.Security.OAuth.Providers源代码库。这似乎相当活跃,并且支持大量其他 oAuth 目标,包括 Slack。

我假设您已经创建并配置了您的 Slack 应用程序。 重定向 URL 部分在这里至关重要,因为无论您指定 http 还是 https 回调(我的示例仅在使用 https 时才有效),这都很重要。

综上所述,我相信实现它的一般方法是

Install-Package AspNet.Security.OAuth.Slack -Version 3.0.0

并像这样编辑您的Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options => { /* your options verbatim */ })
.AddSlack(options =>
{
options.ClientId = "xxx";
options.ClientSecret = "xxx";
});
}

我看到您选择直接在 Startup 类中映射登录/注销路由,这实际上可能是问题所在 - 对 .Map() 的调用会分支请求管道,因此您不会点击您之前设置的相同中间件链),所以我使用了一个单独的 Controller (根据 sample app ):

public class AuthenticationController : Controller
{
[HttpGet("~/signin")]
public async Task<IActionResult> SignIn()
{
// 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 = "/" }, "Slack");
}

[HttpGet("~/signout"), HttpPost("~/signout")]
public IActionResult SignOut()
{
// Instruct the cookies middleware to delete the local cookie created
// when the user agent is redirected from the external identity provider
// after a successful authentication flow (e.g Google or Facebook).
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
CookieAuthenticationDefaults.AuthenticationScheme);
}
}

但是看着你的代码片段,我怀疑你已经安装了这个 nuget 包并尝试使用它。这让我推荐一些需要检查的东西:

  1. 仔细检查 Slack 应用配置中的重定向 URL,
  2. 检查您的应用是否实际启用了 identity.basic 范围
  3. 尝试在单独的 Controller 而不是启动类中处理登录操作
  4. 确保您的应用程序使用 SSL 运行:**项目属性** -> **调试**选项卡 -> **启用 SSL** 复选框(如果 IIS Express 托管,否则您可能需要做 bit of extra work )
  5. 查看the sample project ,它可能会让您了解您的设置有何不同

UPD:经过反复讨论,我能够更好地了解您的问题。我确实相信您所观察到的内容与使用 slack 登录是分开的,而是与他们的应用程序安装流程有关。正如您已经指出的,“添加到 slack”流程和用户登录之间的区别是 - state 参数不是源 URL 的一部分,因此不会跨请求返回给您。这对于 oAuth 处理程序来说意义重大,因为它依赖 state 来验证请求完整性,如果 state 为空,则会失败。有一个discussion on github但我相信的结果是 - 你将不得不自己跳过验证部分。因此,我继承了 nuget 包附带的 SlackAuthenticationHandler 并删除了导致问题的代码:

    public class SlackNoStateAuthenticationHandler : SlackAuthenticationHandler {
public SlackNoStateAuthenticationHandler([NotNull] IOptionsMonitor<SlackAuthenticationOptions> options,
[NotNull] ILoggerFactory logger,
[NotNull] UrlEncoder encoder,
[NotNull] ISystemClock clock) : base(options, logger, encoder, clock) { }

public void GenerateCorrelationIdPublic(AuthenticationProperties properties)
{
GenerateCorrelationId(properties);
}

protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
var query = Request.Query;

var state = query["state"];
var properties = Options.StateDataFormat.Unprotect(state);

var error = query["error"];
if (!StringValues.IsNullOrEmpty(error))
{
// Note: access_denied errors are special protocol errors indicating the user didn't
// approve the authorization demand requested by the remote authorization server.
// Since it's a frequent scenario (that is not caused by incorrect configuration),
// denied errors are handled differently using HandleAccessDeniedErrorAsync().
// Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information.
if (StringValues.Equals(error, "access_denied"))
{
return await HandleAccessDeniedErrorAsync(properties);
}

var failureMessage = new StringBuilder();
failureMessage.Append(error);
var errorDescription = query["error_description"];
if (!StringValues.IsNullOrEmpty(errorDescription))
{
failureMessage.Append(";Description=").Append(errorDescription);
}
var errorUri = query["error_uri"];
if (!StringValues.IsNullOrEmpty(errorUri))
{
failureMessage.Append(";Uri=").Append(errorUri);
}

return HandleRequestResult.Fail(failureMessage.ToString(), properties);
}

var code = query["code"];

if (StringValues.IsNullOrEmpty(code))
{
return HandleRequestResult.Fail("Code was not found.", properties);
}


var tokens = await ExchangeCodeAsync(new OAuthCodeExchangeContext(properties, code, BuildRedirectUri(Options.CallbackPath)));

if (tokens.Error != null)
{
return HandleRequestResult.Fail(tokens.Error, properties);
}

if (string.IsNullOrEmpty(tokens.AccessToken))
{
return HandleRequestResult.Fail("Failed to retrieve access token.", properties);
}

var identity = new ClaimsIdentity(ClaimsIssuer);

if (Options.SaveTokens)
{
var authTokens = new List<AuthenticationToken>();

authTokens.Add(new AuthenticationToken { Name = "access_token", Value = tokens.AccessToken });
if (!string.IsNullOrEmpty(tokens.RefreshToken))
{
authTokens.Add(new AuthenticationToken { Name = "refresh_token", Value = tokens.RefreshToken });
}

if (!string.IsNullOrEmpty(tokens.TokenType))
{
authTokens.Add(new AuthenticationToken { Name = "token_type", Value = tokens.TokenType });
}

if (!string.IsNullOrEmpty(tokens.ExpiresIn))
{
int value;
if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
// https://www.w3.org/TR/xmlschema-2/#dateTime
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value);
authTokens.Add(new AuthenticationToken
{
Name = "expires_at",
Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
});
}
}

properties.StoreTokens(authTokens);
}

var ticket = await CreateTicketAsync(identity, properties, tokens);
if (ticket != null)
{
return HandleRequestResult.Success(ticket);
}
else
{
return HandleRequestResult.Fail("Failed to retrieve user information from remote server.", properties);
}
}
}

此代码的大部分内容都是 relevant source 的逐字副本。 ,因此您可以根据需要随时进行更多更改;

然后我们需要将合​​理的状态参数注入(inject)到您的 URL 中。假设您有一个 Controller 和一个 View :

家庭 Controller

public class HomeController : Controller
{
private readonly IAuthenticationHandlerProvider _handler;

public HomeController(IAuthenticationHandlerProvider handler)
{
_handler = handler;
}

public async Task<IActionResult> Index()
{
var handler = await _handler.GetHandlerAsync(HttpContext, "Slack") as SlackNoStateAuthenticationHandler; // we'd get the configured instance
var props = new AuthenticationProperties { RedirectUri = "/" }; // provide some sane defaults
handler.GenerateCorrelationIdPublic(props); // generate xsrf token and add it into the properties object
ViewBag.state = handler.Options.StateDataFormat.Protect(props); // and push it into your view.
return View();
}
}

启动.cs

.AddOAuth<SlackAuthenticationOptions, SlackNoStateAuthenticationHandler>(SlackAuthenticationDefaults.AuthenticationScheme, SlackAuthenticationDefaults.DisplayName, options =>
{
options.ClientId = "your_id";
options.ClientSecret = "your_secret";
});

索引.cshtml

<a href="https://slack.com/oauth/authorize?client_id=<your_id>&scope=identity.basic&state=@ViewBag.state"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x"></a>

这使我能够成功完成请求,尽管我不完全确定这样做是否会被视为最佳实践

关于c# - 添加到 dotnetcore 中的 Slack,没有 Identity Framework 错误 : The oauth state was missing or invalid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com