如何在identityServer3登录页面中创建验证码

时间:2017-06-06 12:32:27

标签: captcha recaptcha identityserver3

我想在identityServer3的登录页面中使用captcha,我该怎么做? 有样品来源吗? 我尝试使用谷歌reCaptcha但它不起作用。 请帮助我

2 个答案:

答案 0 :(得分:1)

更好的问题是how to customize the login screen?the documentation on customizing views

  

IdentityServer中的视图可以通过以下两种方式之一进行自定义:1)   自定义DefaultViewService提供的HTML模板,或者是否   需要更多控制2)定义自定义IViewService

将自定义IViewService实施为change the full layout。 此外,如果您只想更改登录页面,请添加实现与existing login page相同的角度逻辑的自定义html,并将其添加到名为templates的文件夹中,文件名为_login.html 。 如果要修改layout(标题),则需要在命名文件_Layout.html时执行相同操作。 这一切都在documentation中完成,上面列出了"替换部分视图"。

答案 1 :(得分:1)

这是我不使用IViewService

的方式

将recaptcha脚本添加到Templates / _layout.html头标记

<script src='https://www.google.com/recaptcha/api.js'></script>

在模板/ _login.html中将代码段添加到登录屏幕页面,添加了 name =&#34; g-recaptcha-response&#34; 属性

<div class="g-recaptcha" name="g-recaptcha-response" data-sitekey="your sitekey"></div>

将CspOptions添加到启动类以允许谷歌脚本

CspOptions = new CspOptions
{
    Enabled = true,
    FontSrc = "'self' data: fonts.gstatic.com",
    StyleSrc = "'self' 'unsafe-inline' fonts.googleapis.com",
    ScriptSrc = "'self' https://www.google.com https://www.gstatic.com; object-src 'self'",
    FrameSrc = "https://www.google.com"
}

OwinEnvironmentService注入UserService类 - 这将允许您从reCaptcha片段中获取令牌

private readonly OwinEnvironmentService _environmentService;

public UserService(OwinEnvironmentService environmentService)
{
    _environmentService = environmentService;
}

在AuthenticateLocalAsync中,抓住令牌并验证它

var gReCaptchaResponse = _environmentService.GetLoginInput("g-recaptcha-response");
var client = new RestClient("https://www.google.com");
var request = new RestRequest("recaptcha/api/siteverify", Method.POST) { RequestFormat = DataFormat.Json };
request.AddParameter("secret", "YOUR SECRET");
request.AddParameter("response", gReCaptchaResponse);
var response = client.Execute(request);
var verficationStatus = JsonConvert.DeserializeObject<GReCaptcha>(response.Content);

if(!verficationStatus.Success)
{
    Logger.Warn("Captcha invalid");
    context.AuthenticateResult = new AuthenticateResult("Please verify that you are not a robot");
    return Task.FromResult(0);
}

GetLoginInput(表单输入名称)扩展名 (从Github

的答案中归功于martinip86
public static string GetLoginInput(this OwinEnvironmentService environmentService, string fieldName)
{
    const string body = "owin.RequestBody";
    if (!environmentService.Environment.Keys.Contains(body))
        return null;

    var owinFormData = environmentService.Environment[body] as System.IO.Stream;
    if (owinFormData == null)
        return null;

    var formData = string.Empty;
    using (var sr = new System.IO.StreamReader(owinFormData))
    {
        formData = sr.ReadToEnd();
    }

    if (string.IsNullOrWhiteSpace(formData))
        return null;

    var formDataParsed = HttpUtility.ParseQueryString(formData);
    return formDataParsed[fieldName];
}