简体   繁体   English

始终获得“此请求已被拒绝授权。”消息

[英]Always getting the “Authorization has been denied for this request.” message

I'm able to successfully retrieve token, but when trying to authenticate using the token I always get the Authorization has been denied for this request message. 我能够成功检索令牌,但是当尝试使用令牌进行身份验证时,我总是得到Authorization has been denied for this request消息的Authorization has been denied for this request

My Startup.cs file contains the following methods 我的Startup.cs文件包含以下方法

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    WebApiConfig.Register(config);

    app.UseWebApi(config);

    ConfigureOAuth(app);

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter().First();
    jsonFormatter.SerializerSettings
                 .ContractResolver = new CamelCasePropertyNamesContractResolver();
}

private void ConfigureOAuth(IAppBuilder app)
{
    var oAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/Token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new DefaultAuthorizationServerProvider()
    };

    app.UseOAuthAuthorizationServer(oAuthServerOptions);
    app.UseOAuthBearerAuthentication(new   OAuthBearerAuthenticationOptions());
}

The DefaultAuthorizationServerProvider.cs class contains the following DefaultAuthorizationServerProvider.cs类包含以下内容

public class DefaultAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication
        (
        OAuthValidateClientAuthenticationContext context
        )
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials
        (
        OAuthGrantResourceOwnerCredentialsContext context
        )
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var identityManager = new IdentityManager();

        var identity = identityManager.Get(context.UserName, context.Password,
            new IpAddressProvider().Provide(IpAddressType.Forwarding));

        if (identity == null)
        {
            context.SetError("invalid_grant", "Authentication failed. Please make sure you provided the correct username and password.");
        }
        else
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            context.Validated(identity);
        }
    }
}

And the IdentityManager.cs class have the following IdentityManager.cs类具有以下内容

public class IdentityManager : IIdentityManager
{
    public virtual ClaimsIdentity Get
       (
       string username,
       string password,
       string ipAddress
       )
    {
        var authenticateUserWorkflowOutput = new AuthenticateUserWorkflowHelper().Execute
            (
                new AuthenticateUserWorkflowInput
                {
                    Username = username,
                    Password = password,
                    IpAddress = ipAddress
                },
                new AuthenticateUserWorkflowState()
            );

        if (authenticateUserWorkflowOutput.Message.Exception != null)
        {
            return null;
        }

        if (!authenticateUserWorkflowOutput.Authenticated)
        {
            return null;
        }

        return authenticateUserWorkflowOutput.User != null ? new Infrastructure.Identity(new[]
        {
            new Claim(ClaimTypes.Name, authenticateUserWorkflowOutput.MasterUser.EmailAddress), 
        }, "ApplicationCookie") : null;
    }
}

Using Fiddler I can successfully retrieve a token 使用Fiddler我可以成功检索令牌

在此输入图像描述

But when I try to authenticate using the token I get the following response 但是当我尝试使用令牌进行身份验证时,我得到以下响应

在此输入图像描述

Ok, I found the problem in my Startup class. 好的,我在Startup课程中发现了这个问题。 I was missing the following 我错过了以下内容

[assembly: OwinStartup(typeof(Yugasat.System.ServiceLayer.Startup))]
namespace Yugasat.System.ServiceLayer

and the ConfigureOAuth(app); ConfigureOAuth(app); call needed to be moved to the top of the Configuration method. 需要将调用移动到Configuration方法的顶部。 Below is my new Startup.cs class. 下面是我的新Startup.cs类。

[assembly: OwinStartup(typeof(Yugasat.System.ServiceLayer.Startup))]
namespace Yugasat.System.ServiceLayer
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);

            app.UseWebApi(config);

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new DefaultAuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always “消息”:“此请求已拒绝授权。”OWIN中间件 - “Message”: “Authorization has been denied for this request.” OWIN middleware 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman 始终使用身份2中的不记名令牌获得“对此请求的授权已被拒绝”。 - Always get “Authorization has been denied for this request.” using Bearer tokens in Identity 2? 挥舞着“此请求的授权已被拒绝”消息 - Swagger “Authorization has been denied for this request” message 此请求被拒绝获得授权 - Getting Authorization has been denied for this request 发送承载令牌时,API端点返回“此请求已拒绝授权。” - API end point returning “Authorization has been denied for this request.” when sending bearer token 如何修改“此请求的授权已被拒绝。”使用过滤器HostAuthenticationFilter - How to Modify “Authorization has been denied for this request.” Using filter HostAuthenticationFilter Azure AD 带有用于 Web API 的不记名令牌身份验证的 AD 无法正常工作,抛出错误,因为“此请求的授权已被拒绝”。 - Azure AD with Bearer token authentication for Web API not working throwing error as “Authorization has been denied for this request.” 此请求的C#授权被拒绝 - C# Authorization has been denied for this request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM