Token Webapi C# Auth

Asked

Viewed 265 times

1

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

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

I am passing user and static password

Filing cabinet: 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());
}

Filing cabinet: 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";
        }
    }
}
  • You have an example of request?

  • I edited, including the request;

  • I was referring to the product, for you to check if the token is being generated and shipped

  • Leandro Angelo, I don’t understand, but when I request the token is generated, like bearer.

  • It is exactly what it would be interesting for you to capture, if the token is being generated and included in the bearer

2 answers

0

One of the problems I identified was the reverse line of my method within 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 the right one:

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);
        }

0

In your file Startup.Cs change the passage:

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

for:

app.UseOAuthBearerTokens(optionsConfigurationToken);

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

app.UseCors(CorsOptions.AllowAll);

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

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

app.UseWebApi(config);

In your file Provider

add the override:

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

}

In your file Web.config (extra information to have no problem in the environment of Prod)

add:

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

CALL EXAMPLE:

getting the token:

inserir a descrição da imagem aqui

Calling your API by passing the token

inserir a descrição da imagem aqui

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.