locked
OWIN WebApi Authetication RRS feed

  • Question

  • User-2017229834 posted

    How to create OWIN, token based authentication?

    Thursday, October 10, 2019 7:25 AM

Answers

  • User-2017229834 posted

    Thank you all.. I got this..

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.OAuth;
    using Owin;
    using OwinAuthenticationWebApi.DBAccess;
    using System;
    using System.Collections.Generic;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web.Http;
    
    [assembly: OwinStartup(typeof(OwinAuthenticationWebApi.Startup))]
    
    namespace OwinAuthenticationWebApi
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                ConfigureOAuth(app);
                WebApiConfig.Register(new HttpConfiguration());
                
                // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            }
    
            private void ConfigureOAuth(IAppBuilder app)
            {
                app.CreatePerOwinContext<AuthContext>(() => new AuthContext());
                app.CreatePerOwinContext<UserManager<IdentityUser>>(CreateManager);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/token"),
                    Provider = new AuthorizationServerProvider(),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    AllowInsecureHttp = true,
                });
    
                app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            }
    
            public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
            {
                public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
                {
                    context.Validated();
                }
    
                public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
                {
                    UserManager<IdentityUser> userManager = context.OwinContext.GetUserManager<UserManager<IdentityUser>>();
                    IdentityUser user; // = new IdentityUser { UserName = "admin", Email = "admin@gmail.com" };
                    try
                    {
                        user = await userManager.FindAsync(context.UserName, context.Password);
                    }
                    catch
                    {
                        context.SetError("server_error");
                        context.Rejected();
                        return;
                    }
                    if (user != null)
                    {
                        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                        IDictionary<string, string> CustomProperties = new Dictionary<string, string>
                        {
                            { "userName", user.UserName },
                            { "Email", Convert.ToString(user.Email) }
                        };
                        AuthenticationProperties properties = CreateProperties(CustomProperties);
                        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                        identity.AddClaim(new Claim(ClaimTypes.SerialNumber, user.Email));
    
                        var ticket = new AuthenticationTicket(identity, properties);
                        context.Validated(ticket);
                        await Task.FromResult(0);
                    }
                    else
                    {
                        context.SetError("invalid_grant", "Invalid UserId or password'");
                        context.Rejected();
                    }
                }
            }
    
            private static UserManager<IdentityUser> CreateManager(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
            {
                var userStore = new UserStore<IdentityUser>(context.Get<AuthContext>());
                var owinManager = new UserManager<IdentityUser>(userStore);
                return owinManager;
            }
            public static AuthenticationProperties CreateProperties(IDictionary<string, string> customProperties)
            {
                return new AuthenticationProperties(customProperties);
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 10, 2019 7:56 AM