I am trying to set up Spring Security in Grails authenticating with a token (via the Spring Security REST plugin) and authorizing against LDAP. I have found several examples (I have about 20 browser tabs open right now), but none of them answer the whole question. Most of the examples are Grails + REST Security or Grails + LDAP Security, but no examples of Grails + REST + LDAP.
My issue is that the application tries to look in the database for users and roles, when I need it to look to LDAP.
I found the solution was to go into resources.groovy and configure the userDetailsService bean to use LDAP instead.The only "prerequisite" is that you must already have correct LDAP configurations to your LDAP server. I found this solution here: http://swordsystems.com/2011/12/21/spring-security-cas-ldap/. And only took the following piece.
// Place your Spring DSL code here
import grails.plugin.springsecurity.SpringSecurityUtils
beans = {
def config = SpringSecurityUtils.securityConfig
if (config.ldap.context.server) {
SpringSecurityUtils.loadSecondaryConfig 'DefaultLdapSecurityConfig'
config = SpringSecurityUtils.securityConfig
initialDirContextFactory(org.springframework.security.ldap.DefaultSpringSecurityContextSource,
config.ldap.context.server){
userDn = config.ldap.context.managerDn
password = config.ldap.context.managerPassword
}
ldapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch,
config.ldap.search.base,
config.ldap.search.filter,
initialDirContextFactory){
}
ldapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator,
initialDirContextFactory,
config.ldap.authorities.groupSearchBase){
groupRoleAttribute = config.ldap.authorities.groupRoleAttribute
groupSearchFilter = config.ldap.authorities.groupSearchFilter
searchSubtree = config.ldap.authorities.searchSubtree
rolePrefix = "ROLE_"
convertToUpperCase = config.ldap.mapper.convertToUpperCase
ignorePartialResultException = config.ldap.authorities.ignorePartialResultException
}
userDetailsService(org.springframework.security.ldap.userdetails.LdapUserDetailsService,
ldapUserSearch,
ldapAuthoritiesPopulator){
}
}
}
Related
i've a spring integration java application with a flow configured like this:
String emailStoreUri = emailProtocol + "://" + emailUsername + ":" + emailPassword + "#" + emailHost + ":" + emailPort + "/" + emailFolderInbox;
return IntegrationFlows.from(Mail.imapInboundAdapter(emailStoreUri)
.shouldMarkMessagesAsRead(emailShouldMarkMessagesAsRead)
.simpleContent(true).maxFetchSize(msgPerPoll)
.searchTermStrategy(new AcceptAllEmailStrategy())
.javaMailProperties(p -> {
p.put("mail.store.protocol", emailProtocol);
p.put("mail.debug", emailDebug);
p.put("mail.imaps.timeout", "5000");
p.put("mail.imaps.connectionpoolsize", "1");
p.put("mail.imaps.connectiontimeout", "5000");
p.put("mail.imaps.connectionpool.debug","true");
p.put("mail.debug", "true");
}).simpleContent(true),
e -> e.autoStartup(emailAutoStart).poller(pollerMetadata))
.channel(MessageChannels.rendezvous("inboundEmailChannel")).log("DEBUG").get();
}
This just work for basi auth, how to fix to let this codw work with OAUTH2?
I'm searching online but i didn't find anything about this problem
I somehow think that this is your Gitter question as well: https://gitter.im/spring-projects/spring-integration?at=63ce9304624f3f4330280089.
So, to have a full context over here, please, look into this GH issue: https://github.com/spring-projects/spring-integration-samples/issues/341.
To be precise: you need to implement an Authenticator to obtain OAuth token against the user. Feel free to raise a GH issue, so we will document this approach. Although this has nothing to do with Spring Integration - plain Java Mail feature, - too many people are asking it in Spring Integration context.
Such an Authenticator has to be injected into an ImapMailReceiver via its property:
/**
* Optional, sets the Authenticator to be used to obtain a session. This will not be used if
* {#link AbstractMailReceiver#setSession} has been used to configure the {#link Session} directly.
* #param javaMailAuthenticator The javamail authenticator.
* #see #setSession(Session)
*/
public void setJavaMailAuthenticator(Authenticator javaMailAuthenticator) {
Don't forget to set Java Mail mail.imap.auth.mechanisms=XOAUTH2 property!
I need to call an external API from my spring boot project. The external API is using OAuth 2 security authentication using authorization_code. I have the client id and secret key, any suggestion would be great.
Tried using SDK provided by DocuSign but while getting access token facing issue as 400 with message consent required.
The easiest way to do this is do download a "quickstart" from DocuSign and pick Java for your language. This does a lot more than just give you Java code, it also configures everything you need for you to be able to make API calls.
https://developers.docusign.com/docs/esign-rest-api/quickstart/
The specific Java code that does Auth Code Grant authentication can be found here:
https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/core/controller/GlobalControllerAdvice.java
OAuth2AuthenticationToken oauth = (OAuth2AuthenticationToken) authentication;
OAuth2User oauthUser = oauth.getPrincipal();
OAuth2AuthorizedClient oauthClient = authorizedClientService.loadAuthorizedClient(
oauth.getAuthorizedClientRegistrationId(),
oauthUser.getName()
);
if (oauth.isAuthenticated()) {
user.setName(oauthUser.getAttribute("name"));
if (oauthClient != null){
user.setAccessToken(oauthClient.getAccessToken().getTokenValue());
} else {
user.setAccessToken(((OAuth.OAuthToken) oauthUser.getAttribute("access_token")).getAccessToken());
}
if (account.isEmpty()) {
account = Optional.ofNullable(getDefaultAccountInfo(getOAuthAccounts(oauthUser)));
}
OAuth.Account oauthAccount = account.orElseThrow(() -> new NoSuchElementException(ERROR_ACCOUNT_NOT_FOUND));
session.setAccountId(oauthAccount.getAccountId());
session.setAccountName(oauthAccount.getAccountName());
// TODO set this more efficiently with more APIs as they're added in
String basePath = this.getBaseUrl(apiIndex, oauthAccount) + apiIndex.getBaseUrlSuffix();
session.setBasePath(basePath);
}
Hello I am currently using and old Authorization Server with th end of life dependency spring-security-oauth2-autoconfigure and now i would like to migrate to the new Spring Authorization Server
My questions is how can i intercept/override the default Token Granter of the new Spring Authorization Service. In the old version i just extended the AbstractTokenGranter SsoTokenGranter extends AbstractTokenGranter.
I would like to call other services during the token generation and add custom claims/authorities to the JWT Token with user information(Roles, Name, etc..).
Any tipps how i can do this?
I think an OAuth2TokenCustomizer can fit nicely in your use case.
#Bean
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer(
OidcUserInfoService userInfoService) {
return (context) -> {
if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
OidcUserInfo userInfo = userInfoService.loadUser( // <2>
context.getPrincipal().getName());
context.getClaims().claims(claims ->
claims.putAll(userInfo.getClaims()));
}
};
}
There is a section on the reference docs and a sample that you can use as reference.
After implementing a csrfProtectionMatcher in my Spring Security Configuration in order to just use CSRF tokens on UI facing REST methods I noticed that the logout method configured via
.and()//
.logout()//
.logoutUrl("/logout")//
.deleteCookies("JSESSIONID")//
was not found anymore (404!).
I figured out that I have to register a logoutRequestMatcher:
.and()//
.logout()//
.logoutUrl("/logout")//
.deleteCookies("JSESSIONID")//
.logoutRequestMatcher(request -> {
RegexRequestMatcher logoutRequest = new RegexRequestMatcher("/logout", null);
if (logoutRequest.matches(request)) {
return true;
}
return false;
})//
Can anyone explain why? :)
I have several DC in my LDAP(like DC=Ny, DC=Oh) and would like to authenticate the user from LDAP through grails spring ldap plugin.
Initially I have used following parameters in the config.groovy file and was able to authenticate the users from newyork but now I have to authenticate the users from both newyork and Ohio.
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.test.SecUser'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.test.SecUserSecRole'
grails.plugins.springsecurity.authority.className = 'com.test.SecRole'
// LDAP config
grails.plugins.springsecurity.ldap.context.managerDn = 'CN=P8,OU=P8,OU=Weblogic,OU=PR,OU=Groups - Application,DC=NY,DC=GWL,DC=com'
grails.plugins.springsecurity.ldap.context.managerPassword = 'test'
grails.plugins.springsecurity.ldap.context.server = 'ldap://NY.GWL.com:389/'
grails.plugins.springsecurity.ldap.authorities.ignorePartialResultException = true // typically needed for Active Directory
grails.plugins.springsecurity.ldap.search.base = 'DC=NY,DC=GWL,DC=com'
grails.plugins.springsecurity.ldap.search.filter="sAMAccountName={0}" // for Active Directory you need this
grails.plugins.springsecurity.ldap.search.searchSubtree = true
grails.plugins.springsecurity.ldap.auth.hideUserNotFoundExceptions = false
grails.plugins.springsecurity.ldap.search.attributesToReturn = ['mail', 'displayName'] // extra attributes you want returned; see below for custom classes that access this data
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider', 'anonymousAuthenticationProvider'] // specify this when you want to skip attempting to load from db and only use LDAP
What kind of changes needs to be done in groovy.config file or does I need to do any code changes.
Any help on this will be really helpful.
Thanks