@ Mahe sh Подробнее Пожалуйста, ознакомьтесь с кодом ниже и укажите, где я ошибаюсь:
startup.cs
[assembly: OwinStartup(typeof(AspNet_4_5_2_API.Startup))]
namespace AspNet_4_5_2_API
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
IdentityServerBearerTokenAuthenticationOptions options = new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
AuthenticationType = "Bearer",
RequiredScopes = new[] { "api1" }
};
app.UseIdentityServerBearerTokenAuthentication(options);
}
}
}
Класс контроллера API
namespace AspNet_4_5_2_API.Controllers
{
[Route("identity")]
public class IdentityController : ApiController
{
[HttpGet]
public IHttpActionResult Get()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
return Ok(claims);
}
}
}
Конфигурация клиента в проекте Identity Server
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
// JavaScript Implicit Client
new Client
{
ClientId = "client_id_js",
AllowedGrantTypes = GrantTypes.Implicit,
RedirectUris = { "http://localhost:5004/home/signin" },
PostLogoutRedirectUris = { "http://localhost:5004/home/index" },
AllowedCorsOrigins = { "http://localhost:5004" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1", "tenant", "dateofbirth"
},
//AccessTokenLifetime = 1, //! second for testing
AlwaysIncludeUserClaimsInIdToken = true,
AllowAccessTokensViaBrowser = true,
RequireConsent = false
}
};
}
Javascript Код клиента. При этом функция callApi вызывает проект Web API.
var config = {
userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
authority: "http://localhost:5000",
client_id: "client_id_js",
redirect_uri: "http://localhost:5004/Home/SignIn",
response_type: "id_token token",
scope: "openid api1 dateofbirth tenant",
post_logout_redirect_uri: "http://localhost:5004/Home/Index"
};
var userManager = new Oidc.UserManager(config);
var signIn = function () {
userManager.signinRedirect();
};
var signOut = function () {
userManager.signoutRedirect();
};
userManager.getUser().then(user => {
console.log("user : ", user);
if (user) {
axios.defaults.headers.common["Authorization"] = "Bearer " + user.access_token;
}
});
var callApi = function () {
axios.get("http://localhost:59502/api/identity").then(result => {
console.log(result);
});
};
var refreshing = false;
axios.interceptors.response.use(
function (response) { return response; },
function (error) {
console.log("axios error: ", error.response);
var axiosConfig = error.response.config;
// if error response is 401 try to refresh token
if (error.response.status === 401) {
console.log("axios error 401");
// if already refreshing dont make another request
if (!refreshing) {
console.log("starting token refresh");
refreshing = true;
// do the refresh
return userManager.signinSilent().then(user => {
console.log("new user:", user);
//update the http request and client
axios.defaults.headers.common["Authorization"] = "Bearer " + user.access_token;
axiosConfig.headers["Authorization"] = "Bearer " + user.access_token;
//retry the http request
return axios(axiosConfig);
});
}
}
return Promise.reject(error);
}
);