Web API authentication Bearer token authentication Bearer token authentication

Source: Internet
Author: User

1. Startup.Auth.cs file

Add Property

?
1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; privateset; }

Add a static constructor

?
1 2 3 4 5 6 7 /// <summary> /// 构造函数 /// </summary> static Startup() {     OAuthBearerOptions = new OAuthBearerAuthenticationOptions();}   

Method added in Configureauth

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

2. WebApiConfig.cs file

Method register to add the

?
1 2 config.SuppressDefaultHostAuthentication(); config.Filters.Add(newHostAuthenticationFilter("Bearer"));

3. Create an authentication method (Web API)

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 [HttpPost] public async Task<String> Authenticate(string userName, string password) {     if (string.IsNullOrEmpty(userAccount) || string.IsNullOrEmpty(password))     {         return string.Empty;     }<br>     // 用户查找失败     User user = await UserManager.FindAsync(userName, password);                if (user == null)     {         return string.Empty;     }    // 身份验证票证包括角色或者可以换成用户名     var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);     identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));     if (UserManager.SupportsUserRole)     {         IList<string> roles = await UserManager.GetRolesAsync(user.Id).ConfigureAwait(false);         foreach (string roleName in roles)         {             identity.AddClaim(new Claim(ClaimTypes.Role, roleName, ClaimValueTypes.String));         }     }     AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());     var currentUtc = DateTime.UtcNow;     ticket.Properties.IssuedUtc = currentUtc;     ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));    // 返回值     return Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); }

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

?
1 2 3 4 [Authorize(Roles = "Admin")] public class UsersController : ApiController {}

Test:

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

Authorization:bearer Boqtj0scgz2gfgz ...

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.