I am implementing a Spring OAuth2 application where I have different clients using a resource.
The clients are mobile applications, so I use the Resource Owner Password Flow.
There are 2 roles in my application: normal users and managers. Respectively there are 2 clients, one for the normal users and one for managers.
I don't want to apply logic on the mobile applications (clients) to check if the user has the necessary roles to access the application. As I understood the tokens should be opaque to the client.
I already restrict the resources with user roles, but I don't want the auth server to provide the client with an access code when the user is not supposed to use that client.
How can I restrict authorization for some users on some clients?
Thanks in advance!
oauth config:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().access("#oauth2.clientHasRole('ROLE_MANAGER') and hasRole('ROLE_MANAGER')");
}
}
#Configuration
#EnableWebSecurity
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("demo").password("password").roles("USER")
.and()
.withUser("manager").password("password").roles("MANAGER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
#Configuration
#EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("manager-client")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_MANAGER")
.scopes("trust")
.resourceIds(RESOURCE_ID);
}
}
}
Related
I am using Spring security, oauth in the following way:
#Configuration
#EnableAuthorizationServer
#EnableResourceServer
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.jdbc(jdbcTemplate.getDataSource());
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
configurer.tokenStore(tokenStore())
.reuseRefreshTokens(true)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
I want to now make certain URL's public, so that no token is required to access those resources. For example /public/**
How would I do this? Do I need to use a WebSecurityConfigurerAdapter? Thanks for any help!
UPDATE
I added the WebSecurityConfigurerAdapter as pointed out below. So now the /public/** URL is accessible without any tokens. However, all other endpoints are no longer accessible, and respond with 403 Forbidden
For making the path public/** open without authentication, you can configure the WebSecurityConfigurerAdapter like the following:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/public/**").permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
}
you should have something like this
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login*").permitAll();
}
This is how I solved it:
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers(HttpMethod.GET, "/public/**").permitAll();
http.authorizeRequests().anyRequest().authenticated();
}
}
So far I've had the password grant type and that worked perfectly fine.
Recently I started implementing the Authorization code grant of OAuth in my project. I'm able to get the authorization code from the server. Using the code I'm again able to get the access-token.
The problem is I'm unable to reach the resource server using my access-token. I'm getting redirected to Spring's default /login page everytime I try to access any resource.
Below is the Resource Server:
#Configuration
#PropertySource("classpath:webservices-application.properties")
#EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter{
#Value("${security.oauth2.resource.id}")
private String resourceId;
#Bean
public JdbcTokenStore getTokenStore() {
return new JdbcTokenStore(dataSource);
}
#Autowired
private DataSource dataSource;
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/oauth/**","/login","/").permitAll()
.anyRequest().authenticated();
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(getTokenStore())
.resourceId(resourceId).stateless(false);
}
}
WebSecurity:
#Configuration
#EnableWebSecurity
#EnableOAuth2Sso
public class CustomWebsecurity extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/oauth/**","/login","/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
The AuthorizationServer:
#Configuration
#EnableAuthorizationServer
#EnableOAuth2Sso
protected class AuthorizationApplication extends AuthorizationServerConfigurerAdapter {
#Autowired
public AuthorizationApplication (ApplicationContext applicationContext, AuthenticationManager authenticationManager) {
this.passwordEncoder = applicationContext.getBean(PasswordEncoderImpl.class);
this.authenticationManager = authenticationManager;
}
private PasswordEncoder passwordEncoder;
private AuthenticationManager authenticationManager;
#Bean
protected AuthorizationCodeServices getAuthorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
AuthorizationCodeServices services = getAuthorizationCodeServices();
JdbcTokenStore tokenStore = getTokenStore();
endpoints
.userDetailsService(userDetailsService)
.authorizationCodeServices(services)
.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.approvalStoreDisabled();
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients();
security.passwordEncoder(passwordEncoder);
}
}
The issue might be because of some incorrect configuration of the WebSecurity class. But, I've tried multiple configurations with no luck.
With some guidance from #dur, I was able to reach to the solution.
Here's one of the culprits:
The default order of the OAuth2 resource filter has changed from 3 to SecurityProperties.ACCESS_OVERRIDE_ORDER - 1. This places it after the actuator endpoints but before the basic authentication filter chain. The default can be restored by setting security.oauth2.resource.filter-order = 3
All in all, I made the following changes:
Used #EnableOauth2Client instead of #EnableOAuth2Sso at the ResourceServer as well as the AuthorizationServer, because the latter was giving me the following error:
java.lang.IllegalArgumentException: URI must not be null
Removed CustomWebSecurity and did all the security configurations in the ResourceServer itself.
Change the filter order of the Resource filter by putting the following in the properties file:
security.oauth2.resource.filter-order = 3
Some basic change in the security configuration.
Here's my ResourceServer class now:
#Configuration
#PropertySource("classpath:webservices-application.properties")
#EnableResourceServer
#EnableOAuth2Sso
public class ResourceServer extends ResourceServerConfigurerAdapter{
#Value("${security.oauth2.resource.id}")
private String resourceId;
#Bean
public JdbcTokenStore getTokenStore() {
return new JdbcTokenStore(dataSource);
}
#Autowired
private DataSource dataSource;
#Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.requestMatchers().antMatchers(
"/protected_uri_1",
"/protected_uri_2",
"/protected_uri_3")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and().formLogin();
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(getTokenStore())
.resourceId(resourceId);
}
}
Just like in title, I want that only users of spec. Here is my authentication code:
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().userSearchFilter("(sAMAccountName={0})")
.contextSource(contextSource());
}
I found that there are functions like groupSearchFilter and groupSearchBase or groupRoleAttribute but I have no idea how to use them
I made some modifications on Megha's solution
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Configuration
protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://ip:port/DC=xxxx,DC=yyyy");
contextSource.setUserDn("user_service_account");
contextSource.setPassword("password_user_service_account");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.userSearchBase("OU=Users,OU=Servers")
.userSearchFilter("(&(cn={0})(memberOf=CN=GROUP_NAME,OU=Groups,OU=Servers,DC=xxxx,DC=yyyy))")
.contextSource(contextSource);
}
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").authenticated().and()
.httpBasic();
}
}
"(sAMAccountName={0})"
should be replaced with following
"(&(objectCategory=Person)(sAMAccountName=*)(memberOf=cn=entergroup,ou=users,dc=company,dc=com))"
where cn, ou,dc are the specifications of the group in directory
It depends on how your group membership is set up. Something like the following might work, replacing your group dn and objectclasses as necessary:
groupSearchBase("cn=yourgroup,ou=groups")
groupSearchFilter("(uniqueMember={0})")
I am using Spring Security OAuth2 for authorizations. When trying to refresh the token I get an error: UserDetailsService is required (interestingly I get this error only on unix machines and not on windows). I am using Spring OAuth2 version 2.0.7.
For some reason the AuthenticationManager in the DefaultTokenService is not empty and it tries to authenticate the user to check if he still exists. I think it gets initialized because of some spring security vs. spring oauth2 configuration problems.
I am not using any custom UserDetailsService, hence it should not authenticate the users at this point. However, when I debug it I see that it tries to use one from the WebSecurityConfigurerAdapter and gets to this error. Even if I provide my custom dummy UserDetailsService, it is not using that one, but tries to use the other one, which is null. Am I missing here something? I can not find out why is this happening?
Here is my Oauth2 configuration
#Configuration
#EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
#Autowired
private MySpringTokenStore tokenStore;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private MyClientDetailsServiceImpl clientDetailsService;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore);
endpoints.authenticationManager(authenticationManager)
.approvalStoreDisabled();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients();
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
}
Here is my Spring security configuration
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers("/myRest/events/**", "/events/**", "/events", "/myRest/events").permitAll()
.antMatchers("/login.jsp", "/login").permitAll()
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/myRest/events")).disable()
.sessionManagement().sessionFixation().none();
// #formatter:on
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/index*", "/myRest/events/**", "/events/**", "/myRest/events", "/events", "/swagger/**", "/kibana/**",
"/elastic/**", "/version/**", "/api-docs/**", "/js/**", "/oauth/uncache_approvals", "/oauth/cache_approvals");
}
}
Authorization server endpoint needs UserDetailsService. In your OAuth2Config class configure user details service like the following:
#Autowired
private UserDetailsService userDetailsService;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore);
endpoints.userDetailsService(userDetailsService);
endpoints.authenticationManager(authenticationManager)
.approvalStoreDisabled();
}
You can also configure it in WebSecurityConfigurerAdapter:
#Autowired
private AuthorizationServerEndpointsConfiguration endpoints;
#Override
protected void configure(HttpSecurity http) throws Exception {
if (!endpoints.getEndpointsConfigurer().isUserDetailsServiceOverride()) {
UserDetailsService userDetailsService = http.getSharedObject(UserDetailsService.class);
endpoints.getEndpointsConfigurer().userDetailsService(userDetailsService);
}
// #formatter:off
http
.authorizeRequests()
.antMatchers("/myRest/events/**", "/events/**", "/events", "/myRest/events").permitAll()
.antMatchers("/login.jsp", "/login").permitAll()
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/myRest/events")).disable()
.sessionManagement().sessionFixation().none();
// #formatter:on
}
Adding on to #VijayaNandwana's answer and considering #FilipMajernik's comment,
I created a class for OAuthConfig and made the order less than the class which extends WebSecurityConfigurerAdapter.
#Configuration
#Order(1)
public class OAuthConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private JdbcTemplate jdbcTemplate;
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(jdbcTemplate.getDataSource());
}
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
endpoints.userDetailsService(userDetailsService);
endpoints.authenticationManager(authenticationManager)
.approvalStoreDisabled();
}
}
And Class which extends WebSecurityConfigurerAdapter
#Configuration
#EnableWebSecurity
#Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//Configurations
}
If implementing custom DefaultTokenServices, we don't need UserDetailsService.
#Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
// ...
.tokenServices(tokenServices(endpoints));
}
public AuthorizationServerTokenServices tokenServices(final AuthorizationServerEndpointsConfigurer endpoints) {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
// ...
tokenServices.setAuthenticationManager(
new ProviderManager(List.of(new MyCustomAuthProvider())));
return tokenServices;
}
}
The commit message says:
Add AuthenticationManager to default token services
So that it can be used to check user account changes in a refresh
token grant. If a global UserDetailsService is available it will be
used as a default (e.g. if user has a GlobalAuthenticationConfigurer).
It works by constructing a PreAuthenticationAuthenticationProvider
and using that the authenticate the user in DefaultTokenServices.
To customize that process, users can create their own
DefaultTokenServices and inject an AuthenticationManager.
Fixes gh-401
The authorisation endpoint requires a UserDetailsService.
Add this:
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
endpoints.userDetailsService(userDetailsService);
endpoints.authenticationManager(authenticationManager)
.approvalStoreDisabled();
}
}
I am having some issues getting my application set up using method level annotation controlled by #EnableGlobalMethodSecurity I am using Servlet 3.0 style initialization using
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(MultiSecurityConfig.class);
}
}
I have attempted 2 different ways of initialising an AuthenticationManager both with their own issues. Please note that not using #EnableGlobalMethodSecurity results in a successful server start up and all of the form security executes as expected. My issues arise when I add #EnableGlobalMethodSecurity and #PreAuthorize("hasRole('ROLE_USER')") annotations on my controller.
I am attempting to set up form-based and api-based security independently. The method based annotations need only work for the api security.
One configuration was the following.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").httpBasic();
}
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
}
#Configuration
public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**","/status");
}
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasRole("USER").and()
.formLogin().loginPage("/login").permitAll();
}
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
}
}
This is not ideal as I really want only a single registration of the authentication mechanism but the main issue is that it results in the following exception:
java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
As far as I am aware #EnableGlobalMethodSecurity sets up its own AuthenticationManager so I'm not sure what the problem is here.
The second configuration is as follows.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {
#Bean
protected AuthenticationManager authenticationManager() throws Exception {
return new AuthenticationManagerBuilder(ObjectPostProcessor.QUIESCENT_POSTPROCESSOR)
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN").and()
.and()
.build();
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").httpBasic();
}
}
#Configuration
public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**","/status");
}
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasRole("USER").and()
.formLogin().loginPage("/login").permitAll();
}
}
}
This config actually starts successfully but with an exception
java.lang.IllegalArgumentException: A parent AuthenticationManager or a list of AuthenticationProviders is required
at org.springframework.security.authentication.ProviderManager.checkState(ProviderManager.java:117)
at org.springframework.security.authentication.ProviderManager.<init>(ProviderManager.java:106)
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.performBuild(AuthenticationManagerBuilder.java:221)
and when I test I found that the security doesn't work.
I've been looking at this for a couple of days now and even after diving into spring security implementation code I can't seem to find what is wrong with my configuration.
I am using spring-security-3.2.0.RC1 and spring-framework-3.2.3.RELEASE.
When you use the protected registerAuthentication methods on WebSecurityConfigurerAdapter it is scoping the Authentication to that WebSecurityConfigurerAdapter so EnableGlobalMethodSecurity cannot find it. If you think about this...it makes sense since the method is protected.
The error you are seeing is actually a debug statement (note the level is DEBUG). The reason is that Spring Security will try a few different ways to automatically wire the Global Method Security. Specifically EnableGlobalMethodSecurity will try the following ways to try and get the AuthenticationManager:
If you extend GlobalMethodSecurityConfiguration and override the registerAuthentication it will use the AuthenticationManagerBuilder that was passed in. This allows for isolating the AuthenticationManager in the same way you can do so with WebSecurityConfigurerAdapter
Try to build from the global shared instance of AuthenticationManagerBuilder, if it fails it logs the error message you are seeing (Note the logs also state "This is ok for now, we will try using an AuthenticationManager directly")
Try to use an AuthenticationManager that is exposed as a bean.
For your code, you are going to be best off using something like the following:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {
// Since MultiSecurityConfig does not extend GlobalMethodSecurityConfiguration and
// define an AuthenticationManager, it will try using the globally defined
// AuthenticationManagerBuilder to create one
// The #Enable*Security annotations create a global AuthenticationManagerBuilder
// that can optionally be used for creating an AuthenticationManager that is shared
// The key to using it is to use the #Autowired annotation
#Autowired
public void registerSharedAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
// Since we didn't specify an AuthenticationManager for this class,
// the global instance is used
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.httpBasic();
}
}
#Configuration
public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
// Since we didn't specify an AuthenticationManager for this class,
// the global instance is used
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**","/status");
}
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
}
NOTE: More documentation around this will be getting added to the reference in the coming days.