登录尝试失败会显示登录页面(.loginPage(" / signin"))而不是.failureUrl(" / signin-error")。
当应用程序启动时,显示一个空白页面(带有单词$ END $)而不是登录页面(' / signin')。
Spring Security 4
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("jpaAccountService")
private AccountService accountService;
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().requireCsrfProtectionMatcher(new DefaultRequiresCsrfMatcher())
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/signin")
.loginProcessingUrl("/authenticate")
.failureUrl("/signin-error")
.defaultSuccessUrl("/secure")
.permitAll()
.and()
.apply(new SpringSocialConfigurer())
.and()
.logout()
.logoutUrl("/signout")
.deleteCookies("JSESSIONID")
.logoutSuccessUrl("/signin")
.and()
.rememberMe()
.and()
.authorizeRequests()
.antMatchers("/resources/**","/register").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.invalidSessionUrl("/")
.maximumSessions(1);
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("/connect/yahoo", null);
/* (non-Javadoc)
* @see org.springframework.security.web.util.matcher.RequestMatcher#matches(javax.servlet.http.HttpServletRequest)
*/
@Override
public boolean matches(HttpServletRequest request) {
if(allowedMethods.matcher(request.getMethod()).matches()){
return false;
}
return !unprotectedMatcher.matches(request);
}
}
@Bean(name = "authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean(name="userDetailsService")
@Override
public UserDetailsService userDetailsService() {
return new RepositoryUserDetailsService(accountService);
}
@Bean
public SocialUserDetailsService socialUsersDetailService() {
return new SimpleSocialUsersDetailService(userDetailsService());
}
@Bean
public UserIdSource userIdSource() {
return new AuthenticationNameUserIdSource();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
@Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
}
控制器
@RequestMapping(value = "/signin")
public String signin(Model uiModel){
uiModel.addAttribute("signupForm", new RegistrationForm());
return "signin";
}
@RequestMapping("/signin-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
uiModel.addAttribute("signupForm", new RegistrationForm());
return "signin";
}
登录表格
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<div sec:authorize="hasRole('ROLE_USER')">
<h1>Logged In</h1>
</div>
<div sec:authorize="isAnonymous()">
<p th:if="${loginError}" class="error">Wrong user or password</p>
<div id="login">
<form name="loginForm" th:action="@{/authenticate}" method="post">
<table>
<caption align="left">Login:</caption>
<tr>
<td>Email Address:</td>
<td><input type="text" name="username" value=""/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" value="Login"/></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
</div>
</html>
答案 0 :(得分:1)
确保.authorizeRequests()块在.formLogin()之前出现(由@MosheArad建议)。然后将'.defaultSuccessUrl(“/ secure”)'替换为'.successForwardUrl(“/ /)”。
根目录中有一个index.jsp,它优先于Controller中定义的映射。删除此文件后,重定向开始起作用。
答案 1 :(得分:0)
来自Spring Documentations:
@Configuration
@EnableWebSecurity
public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
.usernameParameter("username") // default is username
.passwordParameter("password") // default is password
.loginPage("/authentication/login") // default is /login with an HTTP get
.failureUrl("/authentication/login?failed") // default is /login?error
.loginProcessingUrl("/authentication/login/process"); // default is /login
// with an HTTP
// post
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
尝试在formLogin
之前放置authorizeRequests为了达到这个目的:
应用程序启动时,显示空白页面而不是登录页面 (&#39; /登入&#39)。
首先,覆盖此方法:
public void configure(WebSecurity web)
throws Exception
在您的安全配置文件中,并使用ignoring()
告诉您的安全机制安全地忽略哪些页面。
Spring Docs中的示例:
webSecurityBuilder.ignoring()
// ignore all URLs that start with /resources/ or /static/
.antMatchers("/resources/**", "/static/**");
在忽略()中你可以在你的黑页上写一个蚂蚁匹配器。
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/");
}
在您的控制器中:
@RequestMapping(value = "/")
public String signin(Model uiModel){
uiModel.addAttribute("signupForm", new RegistrationForm());
return "signin";
}