我正在使用java配置实现spring安全。弹簧安全:登录后重定向到登录页面
在此处提供必要的配置类。
SpringSecurity.java
@Configuration
@EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("IS_AUTHENTICATED_ANONYMOUSLY");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/auth/login").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/auth/login")
.usernameParameter("j_username").passwordParameter("j_password")
.permitAll().successHandler(authenticationSuccessHandler)
.and().httpBasic();
}
}
WebConfig.java
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringConfig.class,SpringSecurity.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
AuthenticationSuccessHandler.java
@Component
public class AuthenticationSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
System.out.println(authentication.getName());
redirectStrategy.sendRedirect(request, response, "/home/homePage");
}
}
SpringConfig.java是所有的数据源和其他包扫描相关的东西被定义,我想这不会在这里需要。
问题是,当点击登录页面url(contextPath)/ auth/login时,它显示我登录页面。但是, 我登录按钮后重定向到相同的登录页面。
我在这里提供了login.jsp。
<form:form action="../home/homePage" class = "form-horizontal">
<legend id = "loginLegend">LOGIN</legend>
<hr style="border: none; height: 1px; color: blue; background: #244363;"/>
UserName: <br>
<input type="text" class="form-control" name="j_username" style = "width: 90% !important; margin-left : 20px;"/><br>
Password:<br>
<input type="password" class = "form-control" name="j_password" style = "width: 90% !important;margin-left : 20px;"/><br>
<button id = "loginButton" class="btn btn-primary" type="submit">Login</button>
</form:form>
Ofcourse它将作为表单提交给'../ home/homePage'而不是处理登录的URL。 –
@ M.Deinum:我已经为控制器中的../home/homePage提供了请求映射。 –
当你点击登录按钮时,你期待它做什么? – Aeseir