c# - Identity 2.0 Web API generate token for client -


i developing asp.net web api application. need authenticate users login , password , return string token in response. need have attribute [authorize] working.

i tried investigate, how using bearertoken mechanism, without success. please provide working code example.

you need configure authorization server (in case authorization server , resource server) issue access tokens , consume them. can done using owin middle-ware defining , end point should sent user credentials (resource owner flow) grant_type = password. validate credentials , provide access token tied expire date configure.

public class startup {     public void configuration(iappbuilder app)     {         configureoauth(app);         //rest of code here;     }      public void configureoauth(iappbuilder app)     {         oauthauthorizationserveroptions oauthserveroptions = new oauthauthorizationserveroptions()         {             allowinsecurehttp = true,             tokenendpointpath = new pathstring("/token"),             accesstokenexpiretimespan = timespan.fromdays(1),             provider = new simpleauthorizationserverprovider()         };          // token generation         app.useoauthauthorizationserver(oauthserveroptions);         // token consumption         app.useoauthbearerauthentication(new oauthbearerauthenticationoptions());      } } 

now need define class named simpleauthorizationserverprovider , validate credentials in method grantresourceownercredentials code below:

public class simpleauthorizationserverprovider : oauthauthorizationserverprovider {     public override async task validateclientauthentication(oauthvalidateclientauthenticationcontext context)     {         context.validated();     }      public override async task grantresourceownercredentials(oauthgrantresourceownercredentialscontext context)     {          context.owincontext.response.headers.add("access-control-allow-origin", new[] { "*" });          using (authrepository _repo = new authrepository())         {             identityuser user = await _repo.finduser(context.username, context.password);              if (user == null)             {                 context.seterror("invalid_grant", "the user name or password incorrect.");                 return;             }         }          var identity = new claimsidentity(context.options.authenticationtype);         identity.addclaim(new claim("sub", context.username));         identity.addclaim(new claim("role", "user"));          context.validated(identity);      } } 

i highly recommend read post here have understanding components installing , how flow works.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -