Owin Authentication in Asp.net MVC Api | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

Owin Authentication in Asp.net MVC Api

Date- Oct 13,2022

5932

Free Download Pay & Download
Owin Authentication Owin

Microsoft Owin

Microsoft Owin is a library introduced by Microsoft for Authentication in projects. It is widely used in api's in Asp.Net projects. So we will see how to implemented owin autnetication in Asp.net MVC Api .

First of all you have to add one new asp.net mvc project and add new api controller in that.

Now you have to go to nuget packages and add these packages

After installing these nuget packages now we will use these libraries for owin authentication.

Now right click on your project and add new class file and  name it Startup.cs and paste this code

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                //The Path For generating the Toekn
                TokenEndpointPath = new PathString("/api/Account/Login/token"),
                //Setting the Token Expired Time (24 hours)
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                //MyAuthorizationServerProvider class will validate the user credentials
                Provider = new AuthorizationServerProvider()
            };

            //Token Generations
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }

TokenEndpointpath - This will have the path which you will use as endpoint for login api and that api will return you a autentication token along with other custom data if needed.

Now  right click on your project and add a new class file and name it AuthorizationServerProvider .

 paste below code in that file for autentication

  public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {


         
            if (string.IsNullOrEmpty(context.UserName) && string.IsNullOrEmpty(context.Password))
            {
             
                context.SetError("invalid_grant", "UserName or Password is missing!");
                return;


            }
            else
            {
                // Add code to check from database
                if (context.UserName != "Admin" || context.Password != "123")
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    return;
                }
            }

            // Add code to get roles from database
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));


            identity.AddClaim(new Claim(ClaimTypes.Name, "TestUser"));



            var props = new AuthenticationProperties(new Dictionary<string, string>
                {

                { "UserName", "TestUser" },
                 { "Id", "1" },

            });
            var newTicket = new AuthenticationTicket(identity, props);
            context.Validated(newTicket);



        }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }


            return Task.FromResult<object>(null);
        }
        public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
        {
            string authenticationToken = context.AccessToken;
            var requestHeaders = context.Request.Headers;

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

As you can see in the GrantResourceOwnerCredentials  method we have to check the credentials from the database and verify the roles and also if it is a valid login. We can pass dynamic username and id and other role values which will be used while generating token.

Now  run the application and go to your postman application and set url and username password like showed in the  image below



You can hit the same endpoint which you have passed in the startup.cs file in the postman api and pass your credentials. You have to remember to keep grant_type password always . And you will see the token in the response. 

So this is how you can add owin authentication in your asp.net api.

Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1190
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts