我正在为我的公司设置一个SSO,为此,我正在使用IdentityServer4 with LdapExtension(这里是示例)。
这允许用户使用ActiveDirectory凭据对任何应用程序进行身份验证
现在的重点是该公司在ASP.NET MVC5 BOILERPLATE with AngularJS中使用应用程序,而我无法使该应用程序理解来自IdentityServer的用户实体
有人可以帮助我实现这一目标吗?
我已经尝试过这种方式
这是我在IdentityServer上的配置:
StartupClass:
public class Startup{
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Env = env;
Configuration = configuration;
}
private IHostingEnvironment Env { get; }
private IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
////.AddSigningCredential(...) // Strongly recommended, if you want something more secure than developer signing (Read The Manual since it's highly recommended)
.AddInMemoryIdentityResources(InMemoryInitConfig.GetIdentityResources())
.AddInMemoryApiResources(InMemoryInitConfig.GetApiResources())
.AddInMemoryClients(InMemoryInitConfig.GetClients())
.AddLdapUsers<OpenLdapAppUser>(Configuration.GetSection("IdentityServerLdap"), UserStore.InMemory);
}
public void Configure(IApplicationBuilder app)
{
if (Env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
我的InMemoryInitConfig:
public class InMemoryInitConfig{
// scopes define the resources in your system
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
//DEMO HTTP CLIENT
new Client
{
ClientId = "demo",
ClientSecrets = new List<Secret> {new Secret("password".Sha256()) } ,
ClientName = "demo",
AllowedGrantTypes = {
GrantType.ClientCredentials, // Server to server
GrantType.ResourceOwnerPassword, // User to server
GrantType.Implicit
},
//GrantTypes.HybridAndClientCredentials,
AllowAccessTokensViaBrowser = true,
AllowOfflineAccess = true,
AccessTokenLifetime = 90, // 1.5 minutes
AbsoluteRefreshTokenLifetime = 0,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
RefreshTokenExpiration = TokenExpiration.Sliding,
UpdateAccessTokenClaimsOnRefresh = true,
RequireConsent = false,
RedirectUris = {
"http://localhost:6234/"
},
PostLogoutRedirectUris = { "http://localhost:6234" },
AllowedCorsOrigins ={ "http://localhost:6234/" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
},
};
}
}
这是我的客户端:
StatupClass:
public class Startup{
public void Configuration(IAppBuilder app)
{
app.UseAbp();
// ABP
//app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);
//app.UseCookieAuthentication(new CookieAuthenticationOptions
//{
// AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
// LoginPath = new PathString("/Account/Login"),
// // evaluate for Persistent cookies (IsPermanent == true). Defaults to 14 days when not set.
// //ExpireTimeSpan = new TimeSpan(int.Parse(ConfigurationManager.AppSettings["AuthSession.ExpireTimeInDays.WhenPersistent"] ?? "14"), 0, 0, 0),
// //SlidingExpiration = bool.Parse(ConfigurationManager.AppSettings["AuthSession.SlidingExpirationEnabled"] ?? bool.FalseString)
// ExpireTimeSpan = TimeSpan.FromHours(12),
// SlidingExpiration = true
//});
// END ABP
#region idsr4
/// IDENTITYSERVER
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
// config do openID
var openIdConfig = new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:5443", //ID Server0
ClientId = "demo",
ClientSecret = "password",
ResponseType = "id_token token",
SignInAsAuthenticationType = "Cookies",
RedirectUri = "http://localhost:6234/", //URL of website when cancel login on idsvr4
PostLogoutRedirectUri = "http://localhost:6234", //URL Logout ??? << when this occor
Scope = "openid profile api1",
RequireHttpsMetadata = false,
// Pega as informações do endpoint de compinfo do identityserver
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async n =>
{
var userInfoClient = new UserInfoClient(
new Uri(n.Options.Authority + "/connect/userinfo"),
n.ProtocolMessage.AccessToken);
var userInfo = await userInfoClient.GetAsync();
// create new identity and set name and role claim type
var nid = new ClaimsIdentity(
n.AuthenticationTicket.Identity.AuthenticationType,
ClaimTypes.GivenName,
ClaimTypes.Role);
// HACK: NAÔ SEI PERCORRER ENUM
foreach (var x in userInfo.Claims)
{
nid.AddClaim(new Claim(x.Item1, x.Item2));
}
// keep the id_token for logout
nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
// add access token for sample API
nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
// keep track of access token expiration
nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));
// add some other app specific claim
//nid.AddClaim(new Claim("app_specific", "some data"));
n.AuthenticationTicket = new AuthenticationTicket(
nid,
n.AuthenticationTicket.Properties);
n.Request.Headers.SetValues("Authorization ", new string[] { "Bearer ", n.ProtocolMessage.AccessToken });
}
}
};
// fim config do openID
app.UseOpenIdConnectAuthentication(openIdConfig);
// END IDENTITYSERVER
#endregion
app.UseExternalSignInCookie("Cookies");
app.MapSignalR();
}
}