In MVC Application, user authentication STS (ADFS) working for one ADFS, but I want to change the all parameter at run time for different ADFS which are configured in Web.config like this :
authority name
validIssuers
issuer (in system.identityModel.services section)
etc
I'm done with this issue.
we can change all following parameters dynamically as below:
FederatedAuthentication.FederationConfiguration.IdentityConfiguration.IssuerNameRegistry = new Trust(trust);
FederatedAuthentication.FederationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost:44300"));
FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.PassiveRedirectEnabled = true;
FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Issuer = "https://sts.domainame.com/adfs/ls/";
FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Realm = "https://localhost:44300";
Trust Class:
public class Trust : IssuerNameRegistry
{
string trust;
public Trust(string trust)
{
this.trust= trust;
}
public override string GetIssuerName(SecurityToken securityToken)
{
return trust;
}
}
Related
I want to use identity server for authenticating and authorizing my users.
I want only for users resource use active directory users and for roles etc I want to use from asp.net identity.
Also i don't want to use windows authentication to authenticate.
I'm using identity server 4 and asp.net core 3.2.
services.AddIdentityServer().AddDeveloperSigningCredential()
//.AddTestUsers(Config.GetUsers())
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryClients(Config.GetClients());
First of all, You need to install below package to use ActiveDirectory features.
Install-Package Microsoft.Windows.Compatibility
Secondly, You need to implement IResourceOwnerPasswordValidator and check user password with ActiveDirectory within that.
public class ActiveDirectoryResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
const string LDAP_DOMAIN = "exldap.example.com:5555";
using (var pcontext = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN, "service_acct_user", "service_acct_pswd"))
{
if (pcontext.ValidateCredentials(context.UserName, context.Password))
{
// user authenticated and set context.Result
}
}
// User not authenticated and set context.Result
return Task.CompletedTask;
}
}
Then register it on Startup.cs
services.AddSingleton<IResourceOwnerPasswordValidator, ActiveDirectoryResourceOwnerPasswordValidator>();
I have a simple spring boot application with two services - ui and resource.
I trying to configure oauth2+oidc authentication using uaa server.
When I login in the ui service, spring security creates authentication result (in OidcAuthorizationCodeAuthenticationProvider) using id_token and it doesn't contain any scopes except openid. When the authentication result is created it contains only one authority - ROLE_USER so a can't use authorization on the client side.
Is is ok to override OidcUserService and add to the user's authorities scopes from the access_token to check access on the client side?
#Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser user = super.loadUser(userRequest);
Collection<? extends GrantedAuthority> authorities = buildAuthorities(
user,
userRequest.getAccessToken().getScopes()
);
return new DefaultOidcUser(
authorities,
userRequest.getIdToken(),
user.getUserInfo()
);
}
Security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers("/protected/**").hasAuthority("SCOPE_protected")
.anyRequest().authenticated()
.and()
.oauth2Login()
.userInfoEndpoint().oidcUserService(oidcUserService())
.and()
...
It works but I'm not sure it's a good idea.
It is the approach as outlined in the Spring Security documentation, so the approach is fine.
The only thing is that when I have implemented it, I didn't add all the scopes to the authorities set - I pulled out the specific claim that had the role information - a custom groups claim that I configured in the identity provider's authorization server.
I include some example code for how to do this with Spring Webflux as most examples show how to do it with Spring MVC as per your code.
note: I'm very inexperienced with using reactor!
public class CustomClaimsOidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcReactiveOAuth2UserService service = new OidcReactiveOAuth2UserService();
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
log.debug("inside CustomClaimsOidcReactiveOAuth2UserService..");
Mono<OidcUser> mOidcUser = service.loadUser(userRequest);
return mOidcUser
.log()
.cast(DefaultOidcUser.class)
.map(DefaultOidcUser::getClaims)
.flatMapIterable(Map::entrySet)
.filter(entry -> entry.getKey().equals("groups"))
.flatMapIterable(roleEntry -> (JSONArray) roleEntry.getValue())
.map(roleString -> {
log.debug("roleString={}", roleString);
return new OidcUserAuthority((String) roleString, userRequest.getIdToken(), null);
})
.collect(Collectors.toSet())
.map(authorities -> {
log.debug("authorities={}", authorities);
return new DefaultOidcUser(authorities, userRequest.getIdToken());
});
}
}
...
#Bean
ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService() {
return new CustomClaimsOidcReactiveOAuth2UserService();
}
I have an ASPNET Core 2 application which I am trying to Authenticate with Azure AD using OpenId. I just have boilerplate code from selecting Single Organization Authentication in the ASPNET Core 2 templates, so no custom code. I followed the article here.
The app is not able to get metadata from the Azure AD application because of proxy. The same URL returns data if I just paste it in browser.
The error I get is:
HttpRequestException: Response status code does not indicate success: 407 (Proxy Authentication Required).
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
IOException: IDX10804: Unable to retrieve document from: 'https://login.microsoftonline.com/my-tenant-id/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever+d__8.MoveNext()
I have another ASPNET 4.5.2 application where I am able to perform authentication with the same Azure AD app as above after setting proxy in code like below:
System.Net.HttpWebRequest.DefaultWebProxy = new WebProxy
{
Address = new Uri("http://my-company-proxy:8080"),
Credentials = new NetworkCredential
{
UserName = "proxyusername",
Password = "proxypassword"
}
};
So Essentially my problem is to get past the Proxy Authentication in ASPNET Core 2.
I have tried Microsoft.AspNetCore.Proxy package. Its pretty much broken and doesn't work for me. Also I tried adding the Proxy entries in machine.config (which are actually not required for 4.5.2 app) but that doesn't work as well. I believe getting past a corporate proxy should be very trivial, but doesn't look like it so far.
Tratcher's comment pointed me in the right direction and I got it working, but just to help everyone with it, below is what you need to do:
builder.AddOpenIdConnect(options => options.BackchannelHttpHandler = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "myusername",
Password = "mypassword"
},
Address = new Uri("http://url:port")
}
});
In Full .net framework setting up a proxy is using a config setting
entry but to use an HTTP proxy in .net core ,you have to implement
IWebProxy interface.
Microsoft.AspNetCore.Proxy is proxy middleware which serves a different purpose (to setup reverse proxy) not as an http proxy .Refer this article for more details
To implement a webproxy in .net core,
public class MyHttpProxy : IWebProxy
{
public MyHttpProxy()
{
//here you can load it from your custom config settings
this.ProxyUri = new Uri(proxyUri);
}
public Uri ProxyUri { get; set; }
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination)
{
return this.ProxyUri;
}
public bool IsBypassed(Uri host)
{
//you can proxy all requests or implement bypass urls based on config settings
return false;
}
}
var config = new HttpClientHandler
{
UseProxy = true,
Proxy = new MyHttpProxy()
};
//then you can simply pass the config to HttpClient
var http = new HttpClient(config)
checkout https://msdn.microsoft.com/en-us/library/system.net.iwebproxy(v=vs.100).aspx
I already have a 5 asp.net application developed under ASP.NET & SQL. each application has his private users tables "credential" to authorize the users on the login.
How can apply a SSO solution to cover the 5 application ? knowing that the same user has different access credential on each application "The username & Password" not same for the same user on the 5 application.
also if there is any third party tool to do that without change any thing on the 5 application, will be very good.
Thanks.
You can use Identity Server for this purpose (here https://identityserver.github.io/Documentation/docsv2/ is documentation for version 3 and you can find there how to run authorization in your APP).
The identity server provide IdentityServerOptions object where you can define some stuff. But for you will be most important Factory property where you can configure Identity Server behavior.
Here is example:
public class Factory
{
public static IdentityServerServiceFactory Create()
{
var factory = new IdentityServerServiceFactory();
// Users are taken from custom UserService which implements IUserService
var userService = new YourUserService();
factory.UserService = new Registration<IUserService>(resolver => userService);
// Custom view service, for custom login views
factory.ViewService = new Registration<IViewService>(typeof(YourViewService));
// Register for Identity Server clients (applications which Identity Server recognize and scopes
factory.UseInMemoryClients(Clients.Get());
factory.UseInMemoryScopes(Scopes.Get());
return factory;
}
}
Where YourUserService will implemtent IUserService (provided by Identity Server) where you can authorize users how you need, in methods AuthenticateLocalAsync and GetProfileDataAsync you can do your own logic for authentication.
And using of the Factory in Startup class for Identity Server project
public void Configuration(IAppBuilder app)
{
var options = new IdentityServerOptions
{
SiteName = "IdentityServer",
SigningCertificate = LoadCertificate(),
EnableWelcomePage = false,
Factory = Factory.Create(),
AuthenticationOptions = new AuthenticationOptions
{
EnablePostSignOutAutoRedirect = true,
EnableSignOutPrompt = false,
},
};
app.UseIdentityServer(options);
}
Here https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/CustomUserService you can find some exmaple of this using own UserService
Also here https://github.com/IdentityServer/IdentityServer3.Samples are more examples how to working with Identity Server.
Only bad thing is that in every application you must configure using Identity Server as authentication service so you must change existing apps.
Can I disable encryption of the request security token response and only manage signatures?
I'm creating a custom STS extending Microsoft.IdentityModel.SecurityTokenService.SecurityTokenService based on the demos of the WIF SDK and I cannot manage to setup not using encryption.
I just ran the "Add STS Reference" wizard in Visual Studio, selecting the option to create a new STS. The template that the tool generated does add support for token encryption, but if no cert is supplied, thne it is disabled: (I left all the default comments)
protected override Scope GetScope( IClaimsPrincipal principal, RequestSecurityToken request )
{
ValidateAppliesTo( request.AppliesTo );
//
// Note: The signing certificate used by default has a Distinguished name of "CN=STSTestCert",
// and is located in the Personal certificate store of the Local Computer. Before going into production,
// ensure that you change this certificate to a valid CA-issued certificate as appropriate.
//
Scope scope = new Scope( request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials );
string encryptingCertificateName = WebConfigurationManager.AppSettings[ "EncryptingCertificateName" ];
if ( !string.IsNullOrEmpty( encryptingCertificateName ) )
{
// Important note on setting the encrypting credentials.
// In a production deployment, you would need to select a certificate that is specific to the RP that is requesting the token.
// You can examine the 'request' to obtain information to determine the certificate to use.
scope.EncryptingCredentials = new X509EncryptingCredentials( CertificateUtil.GetCertificate( StoreName.My, StoreLocation.LocalMachine, encryptingCertificateName ) );
}
else
{
// If there is no encryption certificate specified, the STS will not perform encryption.
// This will succeed for tokens that are created without keys (BearerTokens) or asymmetric keys.
scope.TokenEncryptionRequired = false;
}
// Set the ReplyTo address for the WS-Federation passive protocol (wreply). This is the address to which responses will be directed.
// In this template, we have chosen to set this to the AppliesToAddress.
scope.ReplyToAddress = scope.AppliesToAddress;
return scope;
}
I create a CustomSecurityHandler and override its GetEncryptingCredentials method returning null value like the following lines and it works:
public class MyCustomSecurityTokenHandler : Saml11SecurityTokenHandler
{
public MyCustomSecurityTokenHandler(): base() {}
protected override EncryptingCredentials GetEncryptingCredentials(SecurityTokenDescriptor tokenDescriptor)
{
return null;
}
}
then in the SecurityTokenService class i override the GetSecurityTokenHandler returning the custom class created before:
protected override SecurityTokenHandler GetSecurityTokenHandler(string requestedTokenType)
{
MyCustomSecurityTokenHandler tokenHandler = new MyCustomSecurityTokenHandler();
return tokenHandler;
}