Password mode (Resource Owner Password Credentials Grant) in , Users provide their own user name and password to the client . Clients use this information , towards " Service provider " Asking for authorization . Based on the previous  IdentityServer3 Realization OAuth 2.0 Authorized service 【 Client mode (Client Credentials Grant)】 modify .

client

public class Clients
{
public static List<Client> Get()
{
return new List<Client>
{
// no human involved
new Client
{
ClientName = "App Interface services ",
ClientId = "app_test_id",
Enabled = true,
AccessTokenType = AccessTokenType.Reference,
Flow = Flows.ClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
},
AllowedScopes = new List<string>
{
"user",
"order"
}
},
// human is involved
new Client
{
ClientName = "username client",
ClientId = "irving",
Enabled = true,
AccessTokenType = AccessTokenType.Reference,
Flow = Flows.ResourceOwner,
ClientSecrets = new List<Secret>
{
new Secret("21B5F798-BE55-42BC-8AA8-0025B903DC3B".Sha256())
},
AllowedScopes = new List<string>
{
"user",
"order"
}
}
};
}
}

user

public class Users
{
public static List<InMemoryUser> Get()
{
return new List<InMemoryUser>
{
new InMemoryUser
{
Username = "irving",
Password = "123456",
Subject = "1",
Claims = new[]
{
new Claim(Constants.ClaimTypes.GivenName, "Bob"),
new Claim(Constants.ClaimTypes.FamilyName, "Smith")
}
},
new InMemoryUser
{
Username = "bob",
Password = "secret",
Subject = "2"
},
new InMemoryUser
{
Username = "alice",
Password = "secret",
Subject = "3"
}
};
}
}

Server configuration

public class Startup
{
/// <summary>
/// To configure idsv Authorized service
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
var opts = new IdentityServerOptions
{
SiteName = "Embedded Homeinns PMS 2.0 OAuth2 Service",
EnableWelcomePage = true,
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
//.UseInMemoryUsers(new List<InMemoryUser>()),
.UseInMemoryUsers(Users.Get()),
RequireSsl = false,
//SigningCertificate = new X509Certificate2(string.Format(@"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test")
};
app.UseIdentityServer(opts); /*
// Custom routing
app.Map("/identity", idsrvApp =>
{
idsrvApp.UseIdentityServer(opts);
});
*/
}

controller

[Route("api/v1/values")]
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
var caller = User as ClaimsPrincipal;
var subjectClaim = caller.FindFirst("sub");
if (subjectClaim != null)
{
return Json(new
{
message = "OK user",
client = caller.FindFirst("client_id").Value,
subject = subjectClaim.Value
});
}
else
{
return Json(new
{
message = "OK computer",
client = caller.FindFirst("client_id").Value
});
}
}
}

Console

class Program
{
static void Main(string[] args)
{
/*
POST http://192.168.210.165/connect/token HTTP/1.1
Accept: application/json
Authorization: Basic YXBwX3Rlc3RfaWQ6RjYyMUY0NzAtOTczMS00QTI1LTgwRUYtNjdBNkY3QzVGNEI4
Content-Type: application/x-www-form-urlencoded
Host: 192.168.210.165
Content-Length: 40
Expect: 100-continue
Connection: Keep-Alive grant_type=client_credentials&scope=user
*/ /*
GET http://192.168.210.165:88/api/v1/values HTTP/1.1
Authorization: Bearer 9f82476751e1f8b93f1ea6df7de83b51
Host: 192.168.210.165:88
*/
var log = new LoggerConfiguration()
.WriteTo
.LiterateConsole(outputTemplate: "{Timestamp:HH:mm} [{Level}] ({Name:l}){NewLine} {Message}{NewLine}{Exception}")
.CreateLogger(); //ClientCredentials
var token = new TokenClient(
"http://192.168.210.165/connect/token",
"app_test_id",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
var response = token.RequestClientCredentialsAsync("user").Result;
var client = new HttpClient();
client.SetBearerToken(response.AccessToken);
log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result); //ResourceOwner
var resourceOwnerClient = new TokenClient(
"http://192.168.210.165/connect/token",
"irving",
"21B5F798-BE55-42BC-8AA8-0025B903DC3B");
var data = resourceOwnerClient.RequestResourceOwnerPasswordAsync("irving", "123456", "order").Result;
client.SetBearerToken(data.AccessToken);
log.Information(client.GetStringAsync("http://192.168.210.165:88/api/v1/values").Result);
Console.ReadKey();
}
}
}

be based on IdentityServer3 Realization OAuth 2.0 Authorized service 【 Password mode (Resource Owner Password Credentials)】 More articles about

  1. be based on IdentityServer3 Realization OAuth 2.0 Authorized service 【 Client mode (Client Credentials Grant)】

    github:https://github.com/IdentityServer/IdentityServer3/ documentation:https://identityserver.githu ...

  2. be based on IdentityServer3 Realization OAuth 2.0 Authorization service data persistence

    It took a little time recently , Read IdentityServer Source code , Understand the abstract thinking of the whole project . The importance of object orientation ;  Production environment if you want to use IdentityServer3 , It's mainly about authorized services , Deployment load of resource services ...

  3. Oauth2.0( 6、 ... and ):Resource Owner Password Credentials Authorization and Client Credentials to grant authorization

    These two abbreviations Password The way and Client Way , They are only applicable to the scenario where the application is trusted . A typical example is that different products of the same enterprise should use their own products Oauth2.0 system . In some cases , We hope the product can be customized ...

  4. be based on OWIN WebAPI Use OAuth Authorized service 【 Client authentication authorization (Resource Owner Password Credentials Grant)】

    Scope of application Previously, I introduced Client Credentials Grant , It is only suitable for client mode , No user related . and Resource Owner Password Credentials Grant model ...

  5. OAuth2.0 Study (1-6) Authorization way 3- Password mode (Resource Owner Password Credentials Grant)

    Authorization way 3- Password mode (Resource Owner Password Credentials Grant) Password mode (Resource Owner Password Credentials Grant ...

  6. Use Resource Owner Password Credentials Grant Authorization to issue Token

    The corresponding application scenario is : Develop mobile phones for your own website App( Non third party App), As long as the user is in App On the login , There is no need for users to App Can access the data for authorization . Client acquisition Token: public string Get ...

  7. The first 37 Chapter Resource owner password verification (Resource Owner Password Validation) - Identity Server 4 Chinese document (v1.0.0)

    If you want to use OAuth 2.0 Resource owner password credential Authorization (aka password), You need to implement and register IResourceOwnerPasswordValidator Interface : public interface ...

  8. OAuth Password mode description (resource owner password credentials)

    User to client (third party application) Provide user name and password . Client sends user name and password to authentication server (Authorization server), Request token for the backer (token). Certified clothing ...

  9. understand OAuth 2.0 to grant authorization

    One . What is? OAuth Two . What kind of scene will be used OAuth to grant authorization 3、 ... and .OAuth 2.0 Medium 4 Members Four .OAuth 2.0 Authorization process 5、 ... and .OAuth 2.0 Authorization mode 1.    authorization c ...

Random recommendation

  1. DataTable Transfer to entity

    public class ModelConvertHelper<T> where T : new() { public static IList<T> ConvertToMod ...

  2. Play Built in template tags (1.2.3 edition )http://www.anool.net/?p=617

    a label :  To insert a method connected to the controller html link. as follows : #{a @Application.logout()}Disconnect#{/a} After the template content is parsed, it becomes : <a href=&q ...

  3. ASP.NET Message processing in (MSMQ) Two

    In my last article <ASP.NET Message processing in (MSMQ) One > In the MSMQ Made a popular introduction , Finally, the use of message queue is introduced by sending ordinary text messages and complex object messages .  On this basis, this paper continues to introduce MSMQ Of ...

  4. php-cli Pattern learning (PHP Command line mode )( turn )

    I knew before php—cli The pattern is something like shell Imperative execution php Program , But I always thought it was a backward way , It shouldn't make sense , Because I've never used this before cli Pattern programming . Today, however, we encountered the use of cli Application of pattern . ...

  5. C++ Medium explicitkeyword

    stay C++ Very few people use it in the program explicitkeyword, Undeniable? , It's really rare to use it in daily practice . Besides, C++ Is powerful , Often a problem can make use of several C++ Features to solve . But if you pay a little attention, you'll find what you have ...

  6. VC Miscellany

    get Combobox The state of : towards ComboBox send out CB_GETDROPPEDSTATE news . Format String :char buff[10] ; sprintf(buff,"1+1=%d" ...

  7. ISO7816 Transfer protocol T0 T1

    T=0 The protocol cannot be implemented with a single command , It has to be done in two steps : The first command provides data for the card , Then use another related command to retrieve the data . This brings a lot of trouble to card programming , At the same time, the card memory must retain the data that the last operation needs to return . If you don't ...

  8. prompt Method to display the input dialog

    prompt Method to display the input dialog principle : prompt() Method is used to interact with the user , A dialog box that prompts the user to enter information . prompt(str1,str2); This method contains two properties : str1: Information used to prompt the user for input . ...

  9. PS Teach you to say goodbye to your strong arms

    Step 01 stay Photoshop Open the material picture in the , The places circled in the picture need to be adjusted . Step 02 use [ Lasso tools ] Circle your arms and your surroundings . Step 03 Right click , choice [ emergence ], Set up [ Feather Radius ] by 20 Pixels ...

  10. JavaScript Some functions for string processing in

    crap , Not much to say , Go straight to the code <script type="text/javascript"> (function(){ var methods = { camelize: ...