ASP. NET MVC API Auth

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.