【发布时间】:2021-11-09 18:34:57
【问题描述】:
著名的遗言,但这在我的本地环境中非常有效,但是一旦将其推送到我们的本地服务器,我就会遇到此错误。
这是对我的 .net 服务器的“oauth/token/”路径的调用,在本地这会完美地返回一个令牌。 就像我在标题中所说的那样,我得到一个 200 的代码并返回 1 的有效负载。
Startup.cs
public partial class Startup
{
public ILog log = LogManager.GetLogger(typeof(Startup));
public void Configuration(IAppBuilder app)
{
log.Info("Startup Configuration");
ConfigureOAuth(app);
AreaRegistration.RegisterAllAreas();
var builder = new ContainerBuilder();
// Get your HttpConfiguration.
var config = GlobalConfiguration.Configuration;
WebApiConfig.Register(config);
app.UseWebApi(config);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterControllers(typeof(WebApiApplication).Assembly);
builder.RegisterModule<AutofacWebTypesModule>();
var service = Assembly.GetAssembly(typeof(RatesService));
builder.RegisterAssemblyTypes(service)
.AsImplementedInterfaces()
.InstancePerRequest();
/*
* Registering the Authentication Service here
* because the Authentication filter requires it
*/
builder.RegisterType(typeof(AuthenticationService));
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
FluentCommandConnectionFactory.ConnectionString =
ConfigurationManager.ConnectionStrings["McQuillingWeb"].ConnectionString;
//AuthenticationConfig.Register(config);
}
}
配置身份验证的Startup.Oauth.css
public partial class Startup
{
public void ConfigureOAuth(IAppBuilder app)
{
var issuer = ((NameValueCollection)ConfigurationManager.GetSection("secrets"))["issuer"];
var secret = TextEncodings.Base64Url.Decode(((NameValueCollection)ConfigurationManager.GetSection("secrets"))["secret"]);
app.CreatePerOwinContext(() => new IdentityContext());
app.CreatePerOwinContext(() => new IdentityUserManager());
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { "Any" },
IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
{
new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
}
});
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
#if (DEBUG)
AllowInsecureHttp = true,
#else
AllowInsecureHttp = false,
#endif
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(86400),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(issuer),
});
}
}
CustomOauthProvider 检查凭据
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var request = await context.Request.ReadFormAsync();
IdentityUser user;
var email = request["email"];
if (email != null)
{
user = context.OwinContext.Get<IdentityContext>().Users.FirstOrDefault(u => u.Email == email);
} else
{
user = context.OwinContext.Get<IdentityContext>().Users.FirstOrDefault(u => u.Email == context.UserName);
}
if (!context.OwinContext.Get<IdentityUserManager>().CheckPassword(user, context.Password))
{
context.SetError("invalid_grant", "The user name or password is incorrect");
context.Rejected();
return;
}
var ticket = new AuthenticationTicket(SetClaimsIdentity(context, user, email), new AuthenticationProperties());
context.Validated(ticket);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, IdentityUser user, string email)
{
var identity = new ClaimsIdentity("JWT");
if (email != null)
{
identity.AddClaim(new Claim(ClaimTypes.Name, email));
identity.AddClaim(new Claim("sub", email));
} else
{
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
}
identity.AddClaim(new Claim("aud", "Any"));
var userRoles = context.OwinContext.Get<IdentityUserManager>().GetRoles(user.Id);
foreach (var role in userRoles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
return identity;
}
}
【问题讨论】: