First, Login
<summary>
Get token
</summary>
<param name= "UserName" > Username </param>
<param name= "password" > Password </param>
<returns></returns>
[HttpGet]
public Object Login (string userName, string password)
{
if (verification failed)
Return Json ("User name or password error");
FormsAuthenticationTicket token = new FormsAuthenticationTicket (0, UserName, datetime.now,datetime.now.addhours (1), True,username,
Formsauthentication.formscookiepath);
Returns login results, user information, user authentication ticket information
var token = Formsauthentication.encrypt (token);
Save the identity in the cache and have access valid within one hour
HttpRuntime.Cache.Insert (userName, Token, NULL, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan (1,0,0), System.Web.Caching.CacheItemPriority.Default, NULL);
Return Json (New {token = token});
}
Second, API Auth
Using System.Linq;
Using System.Web;
Using System.Web.Http;
Using System.Web.Http.Controllers;
Using System.Web.Security;
public class apiauthattribute:authorizeattribute//ActionFilterAttribute
{
public override void Onauthorization (Httpactioncontext actioncontext)
{
var content = actioncontext.request.properties["Ms_httpcontext"] as httpcontextbase;
var token = content. request.querystring["Token"];
if (!string. IsNullOrEmpty (token))
{
Decrypts the user ticket and verifies that the user name password matches
if (Validateticket (token))
{
Base. IsAuthorized (Actioncontext);
}
Else
Handleunauthorizedrequest (Actioncontext);
}
Else
Handleunauthorizedrequest (Actioncontext);
}
private bool Validateticket (string encrypttoken)
{
Decryption ticket
var userName = Formsauthentication.decrypt (Encrypttoken). UserData;
var token = HttpRuntime.Cache.Get (userName)?. ToString ();
if (token = = null)
{
return false;
}
Compare the tokens in the session
if (token = = Encrypttoken)
{
return true;
}
return false;
}
}
Iii. add [Apiauth] where verification is required
ASP. NET MVC API Auth