.net – 如何获取客户端DotNetOpenAuth.OAuth2返回的错误消息?
|
我使用ExchangeUserCredentialForToken函数从授权服务器获取令牌。当我的用户存在于我的数据库中时,它的工作正常,但当凭据不正确时,我想向客户端发回一条消息。我使用以下2行代码来设置错误消息: context.SetError("Autorization Error","The username or password is incorrect!");
context.Rejected();
但是在客户端,我只得到协议错误(错误400)。你可以帮助我如何在授权服务器上得到服务器端的错误信息? 授权服务器的完整应用配置: using Constants;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Infrastructure;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using AuthorizationServer.Entities;
using AuthorizationServer.Entities.Infrastructure.Abstract;
using AuthorizationServer.Entities.Infrastructure.Concrete;
namespace AuthorizationServer
{
public partial class Startup
{
private IEmployeeRepository Repository;
public void ConfigureAuth(IAppBuilder app)
{
//instanciate the repository
Repository = new EmployeeRepository();
// Enable Application Sign In Cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Application",AuthenticationMode = AuthenticationMode.Passive,LoginPath = new PathString(Paths.LoginPath),LogoutPath = new PathString(Paths.LogoutPath),});
// Enable External Sign In Cookie
app.SetDefaultSignInAsAuthenticationType("External");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "External",CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",ExpireTimeSpan = TimeSpan.FromMinutes(5),});
// Enable google authentication
app.UseGoogleAuthentication();
// Setup Authorization Server
app.USEOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AuthorizeEndpointPath = new PathString(Paths.AuthorizePath),TokenEndpointPath = new PathString(Paths.TokenPath),ApplicationCanDisplayErrors = true,#if DEBUG
AllowInsecureHttp = true,#endif
// Authorization server provider which controls the lifecycle of Authorization Server
Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri = ValidateClientRedirectUri,OnValidateClientAuthentication = ValidateClientAuthentication,OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,OnGrantClientCredentials = GrantClientCredetails
},// Authorization code provider which creates and receives authorization code
AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,OnReceive = ReceiveAuthenticationCode,},// Refresh token provider which creates and receives referesh token
RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,OnReceive = ReceiveRefreshToken,}
});
// indicate our intent to use bearer authentication
app.USEOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AuthenticationType = "Bearer",AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
});
}
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == Clients.Client1.Id)
{
context.Validated(Clients.Client1.RedirectUrl);
}
else if (context.ClientId == Clients.Client2.Id)
{
context.Validated(Clients.Client2.RedirectUrl);
}
return Task.FromResult(0);
}
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientname;
string clientpassword;
if (context.TryGetBasicCredentials(out clientname,out clientpassword) ||
context.TryGetFormCredentials(out clientname,out clientpassword))
{
employee Employee = Repository.GetEmployee(clientname,clientpassword);
if (Employee != null)
{
context.Validated();
}
else
{
context.SetError("Autorization Error","The username or password is incorrect!");
context.Rejected();
}
}
return Task.FromResult(0);
}
private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(new GenericIdentity(context.UserName,OAuthDefaults.AuthenticationType),context.Scope.Select(x => new Claim("urn:oauth:scope",x)));
context.Validated(identity);
return Task.FromResult(0);
}
private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
{
var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId,x)));
context.Validated(identity);
return Task.FromResult(0);
}
private readonly ConcurrentDictionary<string,string> _authenticationCodes =
new ConcurrentDictionary<string,string>(StringComparer.Ordinal);
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
}
private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
{
string value;
if (_authenticationCodes.TryRemove(context.Token,out value))
{
context.DeserializeTicket(value);
}
}
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
}
}
解决方法这是一个完整的解决方案,使用Jeff的概念与我的原始帖子相结合。1)在上下文中设置错误消息 如果您在设置错误消息后调用context.Rejected(),则会删除错误消息(请参见下面的示例): context.SetError("Account locked","You have exceeded the total allowed failed logins. Please try back in an hour.");
context.Rejected();
您将要从您的任务中删除context.Rejected()。请注意,被拒绝和SetError方法的定义是: 拒绝:
SETERROR:
再次,通过在设置错误后调用Rejected方法,上下文将被标记为没有错误,错误消息将被删除。 2)设置响应的状态代码:使用Jeff的例子,用一点点旋转。 而不是使用魔术字符串,我将创建一个全局属性来设置状态代码的标签。在静态全局类中,创建一个用于标识状态代码的属性(我使用X-Challenge,但是当然可以使用任何您选择的内容)。这将用于标记响应中添加的标题属性。 public static class ServerGlobalVariables
{
//Your other properties...
public const string OwinChallengeFlag = "X-Challenge";
}
然后在您的OAuthAuthorizationServerProvider的各种任务中,您将添加标签作为响应中的新标头值的键。将HttpStatusCode枚举与全局标志结合使用,您将可以访问所有各种状态代码,并避免使用魔术字符串。 //Set the error message
context.SetError("Account locked","You have exceeded the total allowed failed logins. Please try back in an hour.");
//Add your flag to the header of the response
context.Response.Headers.Add(ServerGlobalVariables.OwinChallengeFlag,new[] { ((int)HttpStatusCode.Unauthorized).ToString() });
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – 无法识别的配置部分log4net. web.config网站
- asp.net – 为什么Web API请求的正文读取一次?
- asp.net-mvc – HandleErrorAttribute无法正常工作
- asp.net-mvc – 如何将IoC成员资格提供程序与ASP.NET MVC集
- asp.net-mvc – 在ASP.NET MVC中创建模型
- asp.net – IIS – 无法通过ip地址而不是本地主机访问页面
- asp.net – 如何使用资源文件设置按钮文本
- ASP.NET MVC 2 – ViewModel前缀
- asp.net-mvc – POST操作方法中强类型的ViewModel仅包含空值
- msbuild – 如果不指定目标框架,则不支持“发布”目标
- 在ASP和ASP.Net之间共享登录系统
- asp.net-mvc – 数据库中已经有一个名为“AspNet
- asp.net-mvc – Html.DisplayFor十进制格式?
- datetime – 如何指定模型绑定的日期格式?
- asp.net-web-api – 如何在MVC4 Web API中的自定
- asp.net-mvc – 使用ValueInjecter在具有不同属性
- asp.net – Visual Studio 2015 Web应用程序.NET
- asp.net-mvc-3 – 如何使用Asp.Net MVC 3和Razor
- asp.net-mvc – 如何手动创建简单的成员资格sql表
- asp.net-mvc – 设置下拉项目选择MVC
