0

I am trying to create a login authentication token with webapi via C# and tested it with PostMan

Here is what I done C# webapi

Here is my startup.cs

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Web;
using System.Web.Http;
using Microsoft.Owin.Cors;
using DBSecurityTest.Controllers;

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

namespace DBSecurityTest
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new MyAuthProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


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

MyAuthProvider

using Microsoft.Owin.Security.OAuth;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using DBSecurityTest.Models;

namespace DBSecurityTest.Controllers
{
    public class MyAuthProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            DBSecurityTestEntities DBST = new DBSecurityTestEntities();
            var userdata = DBST.EF_UserLogin(context.UserName, context.Password).FirstOrDefault();
            if (userdata != null)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, userdata.UserRole));
                identity.AddClaim(new Claim(ClaimTypes.Name, userdata.UserName));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                context.Rejected();
            }
        }
    }
}

WebApiConfig

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

namespace DBSecurityTest
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors();
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",


        defaults: new { id = RouteParameter.Optional }
            );


        }
    }
}

I already created my database query as follows:

use [DBSecurityTest]

CREATE TABLE [dbo].[UserLogin](  
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [UserName] [varchar](50) NULL,  
    [UserPassword] [varchar](50) NULL,  
    [UserEmail] [varchar](50) NULL,  
    [UserRole] [varchar](50) NULL,  
 CONSTRAINT [PK_UserLogin] PRIMARY KEY CLUSTERED   
(  
    [Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  

GO  



-- insert data in table  
insert into UserLogin(UserName,UserPassword,UserEmail,UserRole)  
values ('admin','123456','[email protected]','admin')  

-- create store procedure   
Create PROCEDURE [dbo].[EF_UserLogin]   
    @UserName varchar(50)=null,  
    @UserPassword varchar(50)=null  
AS  
BEGIN  

    SET NOCOUNT ON;  

    SELECT  UserName,UserPassword,UserEmail,UserRole from UserLogin where UserName=@UserName and UserPassword=@UserPassword  
END

I already added my ADO.Net Model

The error is that I am unable to tested my token via Postman while I debugging the Api.

My Postman Configuration as follows:

POST, /token I select Body and x.www-form-urlencoded

The error comes with {"error":"unsupported_grant_type"}

Is it my Postman configuration error or that had something to deal with my C# api code?

2 Answers 2

1

Did you write a controller for that? I think you missed out a controller, as storing parameters and handling it. The way you declare it seems that there is no handling at C# WebApi backend there.

I think you can refer some of the video from here: https://www.youtube.com/watch?v=BZnmhyZzKgs

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @user13074015, Ii work with your video, and it worked! Let me get down to the follow API and finished the code. Thanks!!!
0

It's about your request, when you are sending your request using Postman, you should pass a parameter which it is named grant_type.

The OAuth framework specifies several grant types for different use cases, as well as a framework for creating new grant types.

The most common OAuth grant types are listed below.

  • Authorization Code
  • Client Credentials
  • Device Code
  • Refresh Token

for more information read OAuth Grant Types please.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.