WebApi Token C # Auth

1

I am issuing a token, but at the moment making a request with the token, returns the following message:

  

"Message": "Authorization has been denied for this request."

I am passing user and static password

File: startup.cs

private void ConfigureAccessToken(IAppBuilder app)
{
    var optionsConfigurationToken = new OAuthAuthorizationServerOptions()
    {
        //Permitindo acesso ao endereço de fornecimento do token de acesso sem 
        //precisar de HTTPS (AllowInsecureHttp). 
        //Em produção o valor deve ser false.
        AllowInsecureHttp = true,

        //Configurando o endereço do fornecimento do token de acesso (TokenEndpointPath).
        TokenEndpointPath = new PathString("/token"),

        //Configurando por quanto tempo um token de acesso já forncedido valerá (AccessTokenExpireTimeSpan).
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),

        //Como verificar usuário e senha para fornecer tokens de acesso? Precisamos configurar o Provider dos tokens
        Provider = new ProviderTokenAccess()
    };

    //Estas duas linhas ativam o fornecimento de tokens de acesso numa WebApi
    app.UseOAuthAuthorizationServer(optionsConfigurationToken);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

File: Provider

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{   

    var user = Users()
        .FirstOrDefault(x => x.Name == context.UserName
                        && x.Password == context.Password);

    if (user == null)
    {
        context.SetError("invalid_grant",
            "Usuário não encontrado ou a senha está incorreta.");
        return;
    }

    var identyUser = new ClaimsIdentity(context.Options.AuthenticationType);
    identyUser.AddClaim(new Claim("sub", context.UserName));
    identyUser.AddClaim(new Claim(ClaimTypes.Role, "user"));
    context.Validated(identyUser);
}

public static IEnumerable<User> Users()
{
    return new List<User>
    {
        new User { Name = "Marcelo", Password = "admin" },
        new User { Name = "Joao", Password = "12345" },

    };
}

Request

using System.Web.Http;

namespace PlataformaCliAPI.Controllers
{
    public class ContaController : ApiController
    {
        // GET: api/Conta       
        [Authorize]
        public string Get()
        {
            return "Sucesso";
        }
    }
}
    
asked by anonymous 04.10.2018 / 17:04

2 answers

1

In your Startup.cs file change the excerpt:

app.UseOAuthAuthorizationServer(optionsConfigurationToken);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

by:

app.UseOAuthBearerTokens(optionsConfigurationToken);

Configure CORS: The CORS configuration is in the 'Microsoft.Owin.Cors' package

app.UseCors(CorsOptions.AllowAll);

Remove the Defaults settings from the API route and add the following snippet:

   config.MapHttpAttributeRoutes();
   config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional }); 

app.UseWebApi(config);

In your Provider

add override:

   public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult(0);

}

In your Web.config file (extra info so there is no problem in the prod environment)

add:

<add key="OwinStartup" value="[NAMESPACE PARA STARTUP].Startup"/>
<add key="owin:AutomaticAppStartup" value="true" />

EXAMPLES of calls:

getting the token:

CallingyourAPIbypassingthetoken

    
04.10.2018 / 21:38
0

One of the problems I identified was the inverted line of my method inside Startup.cs

Before:

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

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );

            app.UseWebApi(config);    
            ConfigureAccessToken(app);
        }

Then, right:

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

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );

            /*Essa linha precisa ser chamada antes do app.UseWebApi(config);*/
            ConfigureAccessToken(app);
            app.UseWebApi(config);
        }
    
05.10.2018 / 20:49