我使用dao身份验证和自定义身份验证过滤器搜索了Spring安全示例,但我发现,所有示例都使用xml文件配置,
我的问题是如何配置自定义过滤器,即 UsernamePasswordAuthenticationFilter
我的基于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"/>
我想将配置转换为基于 Java配置的配置。 我试过这样做不起作用:
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;
}
}
任何建议如何配置?
谢谢!
答案 0 :(得分:7)
要使用自定义类替换UsernamePasswordAuthenticationFilter,请执行以下操作:
使用以下内容创建新的课程FormLoginConfigurer
(遗憾的是org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer
是最终的,无法延期),请注意对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());
}
}
}
从您的formLogin()
方法移除configure(HttpSecurity)
来电并改为使用以下初始化:
FormLoginConfigurer formLogin = new FormLoginConfigurer();
http.apply(formLogin);
formLogin.loginPage("/auth/login")
.permitAll();
身份验证管理器将自动提供给您的实例
SessionAuthenticationStrategy
来自定义班级中使用的http.sessionManagement()
,也可以为新FormLoginConfigurer
添加逻辑,以便更新您需要的内容另一个选择是将CustomUsernamePasswordAuthenticationFilter
过滤器注册为其他过滤器:
在configure(HttpSecurity http)
方法调用中:
http.addFilter(authFilter());
确保手动配置过滤器的所有选项
要添加自定义AuthenticationProvider
:
覆盖方法configure(AuthenticationManagerBuilder auth)
并添加提供商:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationManagerBean());
}
答案 1 :(得分:0)
你很亲密!
upaf.setAuthenticationManager(".."); //here, how to set AuthenticationManager ??
答案是:
upaf.setAuthenticationManager(authenticationManagerBean());
此外,像这样添加您的自定义:
http
.addFilterBefore(authFilter(), UsernamePasswordAuthenticationFilter.class)