spring-attic / spring-security-javaconfig Goto Github PK
View Code? Open in Web Editor NEWSpring Security Java Configuration Support (to be merged with spring-security-config)
Spring Security Java Configuration Support (to be merged with spring-security-config)
Ensure all the configuration objects can be garbage collected after configuration completes
AuthenticationManager, AuthenticationManagerSecurityBuilder, AuthenticationProvider, DaoAuthenticationProviderSecurityBuilder, etc should be be reduced and we should make fewer
In my business application I am using
the following application stack:
Before trying the new javaconfig implementations,
I have a working business application (as follows) using spring-security.xml.
Furthermore based on the entities / models from database (User, Role, Auth)
and repositories (JpaRepository from spring-data-jpa) only as interfaces,
I have implemented a custom UserDetailsService and AuthenticationProvider,
in which the repositories of the User model is getting @Inject-ed (and some more).
Thus for configurating these, I provided them as beans:
@Bean
public AuthenticationProvider usernamePasswordAuthenticationProvider() {
UsernamePasswordAuthenticationProvider authProv = new UsernamePasswordAuthenticationProvider();
return authProv;
}
@Bean(name = "userDetailsService")
public UserDetailsService passwordUserDetailsService() {
return new PasswordUserDetailsService();
}
Like in some of your examples, I configured these in a similar way:
protected AuthenticationManager authenticationManager(
AuthenticationBuilder authenticationRegistry) throws Exception {
return authenticationRegistry
.add(usernamePasswordAuthenticationProvider())
.userDetails(passwordUserDetailsService()).and()
.build();
}
So far so good, I think the other config is not important at the moment. When I try to start my tomcat server (in eclipse), I noticed in the logs that spring-data-jpa created the required beans, e.g.:
DefaultListableBeanFactory - Overriding bean definition for bean 'userRepository': replacing [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; ...
The next initialized beans are about my beans from java configuration (mvc, view, persistence), e.g.:
AnnotationConfigWebApplicationContext - Bean 'dataSourceConfig' of type [class ...]
After the latter initialization usually the xml from spring security is read and beans are created. In case of the java config of spring security (the test problem now), it is complaining that it cannot inject the upper mentioned userRepository, though working in xml mode. The complete exception chain is listed here:
http://pastebin.com/KK9wXR46
Do you have any idea what the problem could be ?
I thought, maybe your java config is intitializing too early,
that my userRepository bean could not be found (though working in xml mode).
return inMemoryAuthentication(
user("user").password("password").roles("USER"),
user("admin").password("password").roles("USER", "ADMIN")
).authenticationManager();
It doesn't deal with Authentication it is used for AuthenticationManager and it is building...perhaps AuthenticationManagerBuilder
For example ExpressionFilterInvocationSecurityMetadataSourceSecurityBuilder is exessive
@Enable
annotation for web security?Expressions are now part of ExpressionFilterInvocationSecurityMetadataSourceSecurityBuilder
No this isn't consistent w/ preferred builder pattern
We should determine a better name for DefaultSecurityFilterConfigurator and possibly break up the functionality into multiple configurators since we now default in the SimpleWebSecurityConfiguration
configurator.antMatchers("/secure/**").requiresSecure()
.regexMatchers("/insecure/.*").requiresInsecure()
.matchers(custom).requiresSecure();
Put together a branch to demonstrate why builders are used vs just @enable and callback methods.
//cc @rstoyanchev
This will require adding quite a few methods in order to support the expressions (i.e. we must overload for permitAll, authenticated, hasRole, etc)
Once the APIs become a bit more stable, we need to go through and and Java Doc
The following are difficult to read
return springSecurityFilterChain
.apply(formLogin()
.permitAll());
See if there are ways to remove the nesting of (). Perhaps one option would be:
return springSecurityFilterChain
.formLogin()
.permitAll()
.and()
.logout()
.logoutUrl("/custom/logout")
.and()
.apply(new CustomConfigurator())
.something("here");
instead of specifying both arguments in a single method perhaps it could do something like:
builder
.antUrl("/user/**").hasRole("ADMIN")
builder
.anyAntUrl("/signup","/about").permitAll()
builder.
.request(requestMatcher).hasAuthority("ROLE_USER")
To work with @EnableGlobalMethodSecurity should we make the AuthenticationManager reference a bean? It may be better just to allow developers do this (@bean must be present on their implementation anyways). Or we could have the SimpleWebSecurityConfig expose the protected method as a bean and everything reference the Bean reference.
My business application stack is described in issue #50.
There I also have a business model called User.
The old xml spring security configuration supported persistent logins as remember-me service. The default persistent logins service was based on a database table having the
columns: username, token, series, expiredate
This database table did not need the business application and database model demands.
One demand is to use as less database space as possible and directly connecting
the persistent_logins table (or model) to the user model. Thus replace the "username" column by a foreign key column "id_user" (incl. constraint).
These demands involved following implementations:
Ok, now to the SecurityConfig class. The old xml config supported:
<http ...>
[...]
<logout invalidate-session="true"
success-handler-ref="tokenInvalidateLogoutHandler"/>
<remember-me services-ref="rememberMeServices"
key="933500A9-1D54-4B7B-BC0A-3CE2749250A7" />
The used beans are defined as follows:
@Bean
public LogoutSuccessHandler tokenInvalidateLogoutHandler() {
return new TokenInvalidateLogoutHandler();
}
@Bean
public PersistentTokenBasedRememberMeServices rememberMeServices() {
String key = "933500A9-1D54-4B7B-BC0A-3CE2749250A7";
PersistentTokenBasedRememberMeServices rememberMeServices =
new PersistentTokenBasedRememberMeServices(
key, passwordUserDetailsService(), tokenRepository());
rememberMeServices.setAlwaysRemember(true);
return rememberMeServices;
}
@Bean
public PersistentTokenRepository tokenRepository() {
return new UserIdTokenRepository();
}
As far as I have noticed, it is currently not possible to set this service.
Including the results of #50 my current http config is as follows:
protected void configure(HttpConfiguration http) throws Exception {
http
.rememberMe()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/login")
.failureUrl("/login/error")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/login/success", true)
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessHandler(tokenInvalidateLogoutHandler())
.logoutUrl("/logout")
.and()
.sessionManagement()
.maximumSessions(2)
.exceptionIfMaximumExceeded(true)
.expiredUrl("/login");
}
I also read the source code of RememberMeConfigurator.java.
It looks like this "issue" is just a "want to have" to support custom persistent logins:
public RememberMeConfigurator remembeMeServices(RememberMeServices rememberMeServices) {
this.rememberMeServices = rememberMeServices;
return this;
}
I think the key should stay random.
Thanks in advance.
This will allow adding attributes that are specific to the type of FilterInvocationSecurityMetadataSource
This allows for easily overriding existing configurators and registering reasonable defaults.
We should not allow the state of Conifgurators to change once the init phase is done.
Not sure if this needs to be supported, but it is probably best if we do (otherwise the Java Config is not as powerful as it could be)
Ensure all the Spring Security objects can easily use the lifecycle methods and are properly initialized and destroyed
Should we even use permitAll support?
Refine how it works with query parameters
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.