Authorize by Claimidentity by Owin
- Package needed
- Owin
- Microsoft.Owin.Security.OAuth
- Microsoft.Owin.Security.Cookies
- Microsoft.owin
- Microsoft.AspNet.WebApi.Owin
- Startup.cs definition
[assembly:OwinStartup(typeof(GoldWebApi.App_Start.Startup))]namespace GoldWebApi.App_Start{ public class Startup { public void Configuration(IAppBuilder app) { } }}
- By using Cookie
- Add these function call in Startup.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, CookieHttpOnly = false, CookieName = "Auth", ExpireTimeSpan = TimeSpan.FromMinutes(1) });
- Define This action Webapi
[HttpGet] public string Login (string username,string passWord) {string Realpassword = string. Empty; if (Accountdic.trygetvalue (Username,out Realpassword)) {if (PassWord = = Realpassword) {this. SignIn (HttpContext.Current.GetOwinContext (). Authentication, this. Createclaimidentity (UserName)); return "authenticated"; }} return "Deny"; } private void SignIn (Iauthenticationmanager authenticationmanger, claimsidentity identity) {AU Thenticationmanger.signin (New Authenticationproperties () {EXPIRESUTC = DateTime.UtcNow.AddMinut ES (1), ispersistent = true}, identity); } Private Claimsidentity Createclaimidentity (string userName) {return new claimsidentity (new Lis T<claim> () {New Claim (Claimtypes.name, UserName)}, DefaultAuthenticationtypes.applicationcookie); }
4.By Token
- Add these call in Startup.cs
app.UseOAuthBearerAuthentication(GoldWebApi.Controllers.AccountController.OAuthBearerOptions);
- Add these definition in WEBAPI
[HttpGet] public string LoginByTicket(string userName,string passWord) { string realPassword = string.Empty; if (AccountDic.TryGetValue(userName, out realPassword)) { if (passWord == realPassword) { return this.GenerateTicket(this.CreateClaimIdentity(userName)); } } return "Deny"; } private string GenerateTicket(ClaimsIdentity identity) { var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); ticket.Properties.IssuedUtc = DateTime.Now; ticket.Properties.ExpiresUtc = DateTime.Now.AddMinutes(1); return OAuthBearerOptions.AccessTokenFormat.Protect(ticket); }
- by Basic Authentication
- Package Install:Thinktecture.IdentityModel.Owin.BasicAuthentication
- Add these in Startup.cs
app.UseBasicAuthentication("localhost", ValidateUserCredential);public Task<IEnumerable<Claim>> ValidateUserCredential(string userName, string passWord) { return Task.FromResult<IEnumerable<Claim>>(new List<Claim>() { new Claim(ClaimTypes.Name, userName) }); }
Summary
For all those authentication mode, we can use authorize Attribute in our Webapi controller/action to apply the Au Thentication/authorization. Owin The infrustructure job for us.
Authorize by Claimidentity by Owin