[英]How to configure spring security 3.2 to use dao authentication and custom authentication filter using java config
I have googled spring security examples using dao authentication and custom authentication filter, but which are I found, all the examples are using xml file configuration, 我使用dao身份验证和自定义身份验证过滤器搜索了Spring安全示例,但是我发现,所有示例都使用xml文件配置,
My question is how to configure custom filter ie UsernamePasswordAuthenticationFilter 我的问题是如何配置自定义过滤器,即UsernamePasswordAuthenticationFilter
my xml based securityConfig file looks like: 我的基于xml的securityConfig文件如下所示:
<http auto-config="false" use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/auth/login.html" access="permitAll" />
<intercept-url pattern="/auth/logout.html" access="permitAll" />
<intercept-url pattern="/auth/accessDenied.html" access="permitAll" />
<intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN')" />
<intercept-url pattern="/user/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" />
<access-denied-handler error-page="/auth/accessDenied.html"/>
<form-login login-page='/auth/login.html'
default-target-url="/"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
authentication-failure-url="/auth/loginfailed.html" />
<logout success-handler-ref="myLogoutSuccessHandler"
invalidate-session="true" delete-cookies="JSESSIONID" />
<remember-me key="uniqueAndSecret" token-validity-seconds="86400" />
<session-management session-fixation-protection="migrateSession"
session-authentication-error-url="/auth/loginfailed.html">
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="true"
expired-url="/auth/login.html"
session-registry-alias="sessionRegistry"/>
</session-management>
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="com.asn.handler.AsnUrlAuthenticationSuccessHandler" />
<beans:bean id="myLogoutSuccessHandler"
class="com.asn.handler.AsnLogoutSuccessHandler" />
<beans:bean id="userDetailsService" class="com.asn.service.UserDetailsServiceImpl"/>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="encoder"/>
</authentication-provider>
<!-- <authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider> -->
</authentication-manager>
<!-- For hashing and salting user passwords -->
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
I want to convert the configuration's into Java configuration based.. i have tried like this which is doesn't work: 我想将配置转换为基于Java的配置 ..我试过这样做是不行的:
SecurityConfig class: SecurityConfig类:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder encoder;
/*@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception {
logger.info("configureGlobal(AuthenticationManagerBuilder auth) invoked..");
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/resources/**","/assets/**","/files/**").permitAll()
.antMatchers("/auth","/").permitAll()
.anyRequest().authenticated() //every request requires the user to be authenticated
.and()
.formLogin() //form based authentication is supported
.loginPage("/auth/login")
.permitAll()
.and()
.logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/auth/accessDenied");
http.sessionManagement().sessionFixation().migrateSession()
.sessionAuthenticationStrategy(concunSessContAuthStr());
}
@Bean(name="sessionRegistry")
public SessionRegistryImpl sessionRegistryBean(){
logger.info("sessionRegistryBean() invoked..");
return new SessionRegistryImpl();
}
@Bean
public UsernamePasswordAuthenticationFilter authFilter() throws Exception{
logger.info("authFilter() invoked..");
CustomUsernamePasswordAuthenticationFilter upaf = new CustomUsernamePasswordAuthenticationFilter();
upaf.setAuthenticationManager(".."); //here, how to set AuthenticationManager ??
upaf.setSessionAuthenticationStrategy(concunSessContAuthStr());
return upaf;
}
@Bean
public DaoAuthenticationProvider customAuthenticationManagerBean() {
DaoAuthenticationProvider dap = new DaoAuthenticationProvider();
dap.setUserDetailsService(userDetailsService);
dap.setPasswordEncoder(encoder);
return dap;
}
@Bean
public ConcurrentSessionControlAuthenticationStrategy concunSessContAuthStr(){
logger.info("concunSessContAuthStr() invoked..");
ConcurrentSessionControlAuthenticationStrategy cscas= new ConcurrentSessionControlAuthenticationStrategy(sessionRegistryBean());
cscas.setMaximumSessions(2);
cscas.setExceptionIfMaximumExceeded(true);
return cscas;
}
}
Any Suggestions how to configure? 任何建议如何配置?
Thank You! 谢谢!
In order to use a customized class replacing the UsernamePasswordAuthenticationFilter do the following: 要使用替换UsernamePasswordAuthenticationFilter的自定义类,请执行以下操作:
create a new class FormLoginConfigurer
with the following content (the original org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer
is unfortunately final and cannot be extended), notice the call to super(new CustomAuthenticationProcessingFilter(),null)
: 使用以下内容创建一个新类
FormLoginConfigurer
(原始的org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer
很遗憾是最终的,无法扩展),请注意对super(new CustomAuthenticationProcessingFilter(),null)
的调用super(new CustomAuthenticationProcessingFilter(),null)
:
package demo; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; public class FormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractAuthenticationFilterConfigurer<H,FormLoginConfigurer<H>,UsernamePasswordAuthenticationFilter> { public FormLoginConfigurer() { super(new CustomAuthenticationProcessingFilter(),null); usernameParameter("username"); passwordParameter("password"); } public FormLoginConfigurer<H> loginPage(String loginPage) { return super.loginPage(loginPage); } public FormLoginConfigurer<H> usernameParameter(String usernameParameter) { getAuthenticationFilter().setUsernameParameter(usernameParameter); return this; } public FormLoginConfigurer<H> passwordParameter(String passwordParameter) { getAuthenticationFilter().setPasswordParameter(passwordParameter); return this; } @Override public void init(H http) throws Exception { super.init(http); initDefaultLoginFilter(http); } @Override protected RequestMatcher createLoginProcessingUrlMatcher( String loginProcessingUrl) { return new AntPathRequestMatcher(loginProcessingUrl, "POST"); } private String getUsernameParameter() { return getAuthenticationFilter().getUsernameParameter(); } private String getPasswordParameter() { return getAuthenticationFilter().getPasswordParameter(); } private void initDefaultLoginFilter(H http) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http.getSharedObject(DefaultLoginPageGeneratingFilter.class); if(loginPageGeneratingFilter != null && !isCustomLoginPage()) { loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter()); loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl()); } }
} }
remove the formLogin()
call from your configure(HttpSecurity)
method and use the following initialization instead: 从
configure(HttpSecurity)
方法中删除formLogin()
调用,并使用以下初始化:
FormLoginConfigurer formLogin = new FormLoginConfigurer(); http.apply(formLogin); formLogin.loginPage("/auth/login") .permitAll();
the authentication manager will be provided to your instance automatically 身份验证管理器将自动提供给您的实例
SessionAuthenticationStrategy
used in your class by calls to http.sessionManagement()
, or you can add logic to your new FormLoginConfigurer
which updates whatever you need http.sessionManagement()
来自定义类中使用的SessionAuthenticationStrategy
,或者您可以向新的FormLoginConfigurer
添加逻辑,以更新您需要的任何内容 Another option is to register your CustomUsernamePasswordAuthenticationFilter
filter as an additional filter: 另一种选择是将
CustomUsernamePasswordAuthenticationFilter
过滤器注册为附加过滤器:
in the configure(HttpSecurity http)
method call: 在
configure(HttpSecurity http)
方法调用中:
http.addFilter(authFilter());
make sure to configure all options of the filter manually 确保手动配置过滤器的所有选项
In order to add a custom AuthenticationProvider
: 要添加自定义
AuthenticationProvider
:
override method configure(AuthenticationManagerBuilder auth)
and add the provider: 覆盖方法
configure(AuthenticationManagerBuilder auth)
并添加提供者:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationManagerBean()); }
You are close ! 你很近!
upaf.setAuthenticationManager(".."); //here, how to set AuthenticationManager ??
The answer is : 答案是 :
upaf.setAuthenticationManager(authenticationManagerBean());
Also, add your Custom like this : 另外,像这样添加您的自定义:
http
.addFilterBefore(authFilter(), UsernamePasswordAuthenticationFilter.class)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.