Возврат авторизации tojen Web API 2, OWIN, OAuth, IdentityModel «Авторизация отклонена для этого запроса» - PullRequest
0 голосов
/ 27 июня 2019

Я пытаюсь понять учебник, которому я следую, чтобы попытаться понять этот тип авторизации. После получения токена. Через почтальона, когда я пытаюсь попасть в одну из конечных точек, требующих авторизации. Я продолжаю получать: «В этом запросе отказано в авторизации»

Я застрял на этом некоторое время, так как я не смог понять, что на самом деле происходит и где я иду не так.

Вот код из автозагрузки .cs

 public class Startup
{
    private string _issuer = ConfigurationManager.AppSettings["issuer"];

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);

        ConfigureWebApi(httpConfig);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(httpConfig);
    }

    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            //For Dev enviroment only (on production should be AllowInsecureHttp = false)
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat = new CustomJwtFormat(_issuer)
        };

        // OAuth 2.0 Bearer Access Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {


        string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
        byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new SymmetricKeyIssuerSecurityKeyProvider(_issuer, audienceSecret)
                }
            });
    }

    private void ConfigureWebApi(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

вот код из customAuthProvider

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        string clientId = string.Empty;
        string clientSecret = string.Empty;
        string symmetricKeyAsBase64 = string.Empty;

        if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
        {
            context.TryGetFormCredentials(out clientId, out clientSecret);
        }

        if (context.ClientId == null)
        {
            context.SetError("invalid_clientId", "client_Id is not set");
            return Task.FromResult<object>(null);
        }

        var audience = AudiencesStore.FindAudience(context.ClientId);

        if (audience == null)
        {
            context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
            return Task.FromResult<object>(null);
        }

        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        //var allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        if (!user.EmailConfirmed)
        {
            context.SetError("invalid_grant", "User did not confirm email.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

        var ticket = new AuthenticationTicket(oAuthIdentity, null);

        context.Validated(ticket);

    }
}

Вот код из CustomJwtFormat

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
    private readonly string _issuer = string.Empty;

    public CustomJwtFormat(string issuer)
    {
        _issuer = issuer;
    }

    public string Protect(AuthenticationTicket data)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];

        string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"];

        var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
        var secKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(symmetricKeyAsBase64));
        var signingKey = new Microsoft.IdentityModel.Tokens.SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);


        var issued = data.Properties.IssuedUtc;

        var expires = data.Properties.ExpiresUtc;

        var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

        var handler = new JwtSecurityTokenHandler();

        var jwt = handler.WriteToken(token);

        return jwt;
    }

    public AuthenticationTicket Unprotect(string protectedText)
    {
        throw new NotImplementedException();
    }
}

После этого учебного пособия все шло хорошо до конца части 3. Тестирование реализации для попытки изменить пароль и каждый раз, когда получен ответ: «Авторизация была отклонена для этого запроса «

enter image description here

Я также справлялся с подобными вопросами, но предоставленные ответы так и не помогли мне преодолеть это препятствие.

...