1. Startup.Auth.cs file
Add Property
public static oauthbearerauthenticationoptions oauthbeareroptions {get; private set;}
Add a static constructor
<summary> ///constructor///</summary> static Startup () { oauthbeareroptions = new Oauthbearerauthenticationoptions (); }
Method added in Configureauth
Use an anonymous authentication app. Useoauthbearerauthentication (oauthbeareroptions);
2. WebApiConfig.cs file
Method register to add the
Config. Suppressdefaulthostauthentication (); Config. Filters.add (New Hostauthenticationfilter ("Bearer"));
3. Create an authentication method (Web API)
[HttpPost] public async task<string> Authenticate (string userName, string password) {if (s Tring. IsNullOrEmpty (useraccount) | | String. IsNullOrEmpty (password)) {return string. Empty; }
User Lookup failed users user = await Usermanager.findasync (userName, password); if (user = = null) {return string. Empty; }//The authentication ticket includes a role or can be replaced with a username var identity = new Claimsidentity (Startup.OAuthBearerOptions.Authentication Type); 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 value returns Startup.OAuthBearerOptions.AccessTokenFormat.Protect (ticket); }
4. Add a tag for a controller or method that requires authentication
[Authorize (Roles = "Admin")]public class userscontroller:apicontroller{}
Test:
Add a token to the request header in the following format:
Authorization:bearer Boqtj0scgz2gfgz ...
Web API authentication Bearer token authentication Bearer token authentication