akc*_*soy 9 spring spring-mvc spring-security thymeleaf
这是我的WebAppInitializer:
@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppConfig.class, WebSecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.authorizeRequests()
.antMatchers("/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/home").failureUrl("/error").permitAll()
.and().httpBasic();
// @formatter:on
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的login.html(来自thymeleaf的示例html):
<form th:action="@{/j_spring_security_check}" method="post">
<label for="j_username">Username</label>:
<input type="text" id="j_username" name="j_username" /> <br />
<label for="j_password">Password</label>:
<input type="password" id="j_password" name="j_password" /> <br />
<input type="submit" value="Log in" />
</form>
Run Code Online (Sandbox Code Playgroud)
当我点击登录时,会出现此错误:
HTTP ERROR 404
Problem accessing /j_spring_security_check. Reason:
Not Found
Run Code Online (Sandbox Code Playgroud)
我怎样才能摆脱这个错误?我google了很多,但还没有成功.(是的,我不使用任何xml.)
Tan*_*rma 19
如果你使用spring 4.X那么可能是版本问题
a.)login url =/login b.)logout url =/logout
弹簧3.X的情况
a.)login url =/j_spring_security_check b.)logout url =/j_spring_security_logout
我创建了这个,它现在有效:
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
Run Code Online (Sandbox Code Playgroud)
这会激活SpringSecurityFilterChain.
由于CSRF错误,我还必须从@EnableWebSecurity切换到@EnableWebMvcSecurity.正如在春季文档写的:
...原因是Spring Security正在防范CSRF攻击,并且我们的请求中没有包含CSRF令牌.更新我们的配置以使用@EnableWebMvcSecurity批注,它将与@EnableWebMvcSecurity一样,并提供与Spring MVC的集成.除此之外,当使用Thymleaf 2.1+或Spring MVC标签库时,它将确保我们的CSRF令牌自动包含在我们的表单中...
还要感谢M. Deinum的评论.Spring最近显然将/ j_spring_security_check/j_password/j_username切换为/ login/password/username.
| 归档时间: |
|
| 查看次数: |
14853 次 |
| 最近记录: |