我正在使用java配置实现spring security。
在此处提供必要的配置类。
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>
因此,您现在所拥有的以及您期望它如何工作的一些问题。
首先,您需要将登录页面指向将处理登录表单的网址(如果需要,可以自定义)。
其次,如果您希望用户始终以“ / home / homePage”结尾,则只需添加 loginSuccessURL("/home/homePage");
否则,您可以做的只是将antMatcher(“ / home / homePage”)设置为预期的角色,除非用户通过身份验证,否则它将始终请求登录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句