ASP. NET Web API authentication bearer token verification Bearer token authentication Simple implementation

Source: Internet
Author: User

1. Startup.Auth.cs file

Add Property

1 publicstatic OAuthBearerAuthenticationOptions OAuthBearerOptions { getprivateset; }

Add a static constructor

1234567 /// <summary>/// 构造函数/// </summary>staticStartup(){    OAuthBearerOptions = newOAuthBearerAuthenticationOptions();}   

Method added in Configureauth

12 // 使用不记名身份验证app.UseOAuthBearerAuthentication(OAuthBearerOptions);

2. WebApiConfig.cs file

Method register to add the

12 config.SuppressDefaultHostAuthentication();config.Filters.Add(newHostAuthenticationFilter("Bearer"));

3. Create an authentication method (Web API)

123456789101112131415161718192021222324252627282930313233 [HttpPost]publicasync Task<String> Authenticate(stringuserName, stringpassword){    if(string.IsNullOrEmpty(userAccount) || string.IsNullOrEmpty(password))    {        returnstring.Empty;    }<br>    // 用户查找失败    User user = await UserManager.FindAsync(userName, password);               if(user == null)    {        returnstring.Empty;    }     // 身份验证票证包括角色或者可以换成用户名    varidentity = newClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);    identity.AddClaim(newClaim(ClaimTypes.NameIdentifier, user.Id.ToString()));    if (UserManager.SupportsUserRole)    {        IList<string> roles = await UserManager.GetRolesAsync(user.Id).ConfigureAwait(false);        foreach(stringroleName inroles)        {            identity.AddClaim(newClaim(ClaimTypes.Role, roleName, ClaimValueTypes.String));        }    }    AuthenticationTicket ticket = newAuthenticationTicket(identity, newAuthenticationProperties());    varcurrentUtc = DateTime.UtcNow;    ticket.Properties.IssuedUtc = currentUtc;    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));     // 返回值    returnStartup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);}

4. Add a tag for a controller or method that requires authentication

1234 [Authorize(Roles = "Admin")]publicclassUsersController : ApiController{}

Test:

Add a token to the request header in the following format:

Authorization:bearer Boqtj0scgz2gfgz ...

Category: Web API

ASP. NET Web API authentication bearer token verification Bearer token authentication Simple implementation

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.