Web API中基于令牌的身份验证

这篇是翻译文,翻译原文来自:https://dotnettutorials.net/lesson/token-based-authentication-web-api/

Web API中基于令牌的身份验证

 

 

 步骤1:建立数据库

Web API中基于令牌的身份验证

 

 

 步骤2:建立空的Web API项目

Web API中基于令牌的身份验证

 

 

 

Web API中基于令牌的身份验证

 

步骤3:通过NuGet添加引用

Web API中基于令牌的身份验证

 

 

 步骤4:创建ADO.NET实体数据模型

Entity Framework数据库优先的方法

步骤5:建立仓储类

 1 namespace TokenAuthenticationWEBAPI.Models
 2 {
 3     public class UserMasterRepository : IDisposable
 4     {
 5         DailyTestEntities context = new DailyTestEntities();
 6         public UserMaster ValidateUser(string username, string password)
 7         {
 8             return context.UserMaster.FirstOrDefault(user => user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase) && user.UserPassword == password);
 9         }
10         public void Dispose()
11         {
12             context.Dispose();
13         }
14     }
15 }

步骤6:添加一个类,用于验证询问令牌的用户凭据。(Step6: Add a class for validating the user credentials asking for tokens.)

namespace TokenAuthenticationWEBAPI.Models
{
    public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserMasterRepository _repo = new UserMasterRepository())
            {
                var user = _repo.ValidateUser(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    return;
                }
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRoles));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim("Email", user.UserEmailID));
                context.Validated(identity);
            }
        }
    }
}

一些必要的解释:

Web API中基于令牌的身份验证

 

 

Web API中基于令牌的身份验证

 

 Web API中基于令牌的身份验证

 

 

Web API中基于令牌的身份验证

 

 Web API中基于令牌的身份验证

 

Web API中基于令牌的身份验证

 

 

步骤七:添加OWINStartup类

Web API中基于令牌的身份验证

 

 Web API中基于令牌的身份验证

 

 

namespace TokenAuthenticationWEBAPI
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            // Enable CORS (cross origin resource sharing) for making request using browser from different domains
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                //The Path For generating the Toekn
                TokenEndpointPath = new PathString("/token"),
                //Setting the Token Expired Time (24 hours)
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                //MyAuthorizationServerProvider class will validate the user credentials
                Provider = new MyAuthorizationServerProvider()
            };
            //Token Generations
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

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

必要的解释:Web API中基于令牌的身份验证

 

 

步骤8:添加Web API Controller

Web API中基于令牌的身份验证

 

 

namespace TokenAuthenticationWEBAPI.Controllers
{
    public class TestController : ApiController
    {
        //This resource is For all types of role
        [Authorize(Roles = "SuperAdmin, Admin, User")]
        [HttpGet]
        [Route("api/test/resource1")]
        public IHttpActionResult GetResource1()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok("Hello: " + identity.Name);
        }
        //This resource is only For Admin and SuperAdmin role
        [Authorize(Roles = "SuperAdmin, Admin")]
        [HttpGet]
        [Route("api/test/resource2")]
        public IHttpActionResult GetResource2()
        {
            var identity = (ClaimsIdentity)User.Identity;
            var Email = identity.Claims
                      .FirstOrDefault(c => c.Type == "Email").Value;
            var UserName = identity.Name;

            return Ok("Hello " + UserName + ", Your Email ID is :" + Email);
        }
        //This resource is only For SuperAdmin role
        [Authorize(Roles = "SuperAdmin")]
        [HttpGet]
        [Route("api/test/resource3")]
        public IHttpActionResult GetResource3()
        {
            var identity = (ClaimsIdentity)User.Identity;
            var roles = identity.Claims
                        .Where(c => c.Type == ClaimTypes.Role)
                        .Select(c => c.Value);
            return Ok("Hello " + identity.Name + "Your Role(s) are: " + string.Join(",", roles.ToList()));
        }
    }
}

步骤9:测试令牌的认证(用PostMan)

 

Web API中基于令牌的身份验证

上一篇:C#语法基础01_读取输入


下一篇:AcWing 240. 食物链