问题
This may be a dumb question, but here goes :)
I have the following applications in this problem:
- An IdentityServer3
- A WebApi2 application which uses the Identityserver as its authenticator
- MVC web app
What I want to do, is to call a secured service on the WebApi from the IdentityServer, but in order to do so I require an access token.
How do I within the IdentityServer issue an access token to itself (which in order will be authenticated through itself from the WebApi)
回答1:
IdentityServer includes an OWIN extension method that allows issuing tokens directly - no need to go through one of the protocol flows.
It is called IssueClientToken
and is documented here:
https://identityserver.github.io/Documentation/docsv2/advanced/owin.html
回答2:
I have the same, or very similar requirement. In my case, a user requests a token and is authenticated using an external IdP (this is using authcode flow). Just after the user authentication process I need IdentityServer to contact the secured WebApi - and in doing so IdentityServer needs a token (using Client Credentials flow)
My current solution (but I am still testing) is to make the call within AutenticateExternalAsync on a custom User Service. Here I make a call using TokenClient.RequestClientCredentialsAsync. Obviously, a client needs setting up for IdentityServer itself.
Early indications are that this works as expected in a dev environment.
回答3:
I followed the suggestion from @Andy and it worked for me :) Posting my code here for others to see. The following code is implemented in a custom User Service.
public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
var user = GetUsersAsync().SingleOrDefault(x => x.Username == context.UserName && x.Password == context.Password);
if (user != null)
{
context.AuthenticateResult = new AuthenticateResult(user.Subject, user.Username);
}
return Task.FromResult(0);
}
private static List<CustomUser> GetUsersAsync()
{
var response = GetTokenAsync();
var result = CallUserApi(response.Result.AccessToken).Result;
var users = JsonConvert.DeserializeObject<List<CustomUser>>(result);
return users;
}
private static Task<string> CallUserApi(string token)
{
var client = new HttpClient();
client.SetBearerToken(token);
var json = client.GetStringAsync($"https://your.apiAdress.here/");
return json;
}
private static Task<IdentityModel.Client.TokenResponse> GetTokenAsync()
{
var client = new TokenClient(
"https://identityserver.adress.here/identity/connect/token",
"clientId",
"secret");
return client.RequestClientCredentialsAsync("apiScope");
}
来源:https://stackoverflow.com/questions/38768088/how-can-i-issue-an-access-token-to-the-identityserver-itself