【问题标题】:OAuthAuthorizationServerProvider returns 200 with 1 as payloadOAuthAuthorizationServerProvider 返回 200 和 1 作为有效负载
【发布时间】: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;
    }
}

【问题讨论】:

    标签: asp.net oauth jwt


    【解决方案1】:

    更新:我对存储我的凭据的数据库没有适当的权限。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2018-12-15
    • 2014-07-31
    • 2022-11-19
    • 2019-10-23
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多