locked
When trying to generate token using POSTMAN, i got error as "error": "invalid_grant". RRS feed

  • Question

  • User50299930 posted

    Hi,

    I am new to WEBAPI. I created new webapi project and implemented code for login and logout with oauth authentication.

    I ran my WEBAPI application. Now I want to generate a token using postman.

    In postman selected POST request and added URL as http://localhost:54563/token

    Selected BODY with radio button x-www-form-urlencoded.

    Gave key and values as below

    username: test

    password: 123

    grant_type:password

    Now clicked on SEND button.

    I got error as 

    {
    "error": "invalid_grant"
    }

    Status: 400 BAD REQUEST.

    can any one help me how to resolve it?

    using System;
    using System.Threading.Tasks;
    using Microsoft.Owin;
    using Owin;
    using Microsoft.Owin.Cors;
    using Microsoft.Owin.Security.OAuth;

    [assembly: OwinStartup(typeof(WEBAPIReg.Startup))]

    namespace WEBAPIReg
    {
    public class Startup
    {
    public void Configuration(IAppBuilder app)
    {
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
    app.UseCors(CorsOptions.AllowAll);

    OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
    {
    TokenEndpointPath = new PathString("/token"),
    Provider = new ApplicationOAuthProvider(),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
    AllowInsecureHttp = true
    };

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

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.Owin.Security.OAuth;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using WEBAPIReg.Models;

    namespace WEBAPIReg
    {
    public class ApplicationOAuthProvider : 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 userStore = new UserStore<ApplicationUser>(new applicationDbContext());
    var manager = new UserManager<ApplicationUser>(userStore);
    var user = await manager.FindAsync(context.UserName, context.Password);
    if (user != null)
    {
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim("Username", user.UserName));
    identity.AddClaim(new Claim("Email", user.Email));
    identity.AddClaim(new Claim("FirstName", user.FirstName));
    identity.AddClaim(new Claim("LastName", user.LastName));
    identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
    }
    else
    return;
    }
    }
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Http.Cors;

    namespace WEBAPIReg
    {
    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    // Web API configuration and services
    //config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));
    // Web API routes
    config.MapHttpAttributeRoutes();

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

    public class AccountModel
    {
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    }

    Regards

    Ramki

    Thursday, May 2, 2019 7:31 AM

All replies

  • User475983607 posted

    We cannot reproduce this issue without your source code.

    Thursday, May 2, 2019 10:33 AM
  • User50299930 posted

    Hi,

    I added my webapi code.

    Thursday, May 2, 2019 1:23 PM
  • User36583972 posted

    Hi krishn451,

    I am new to WEBAPI. I created new webapi project and implemented code for login and logout with oauth authentication.

    I suggest you can refer the Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2 sample and make a test on your side.

    The Log In button sends a request to the token endpoint. The body of the request contains the following form-url-encoded data:
    
    grant_type: "password"
    username: <the user's email>
    password: <password>
    

    Best Regards

    Yong Lu

    Friday, May 3, 2019 9:11 AM
  • User50299930 posted

    will try with your suggestion.

    thank you.

    Wednesday, May 8, 2019 12:41 PM