我使用的是Spring Security 4.1.1,我遇到了问题:我尝试访问URL,应用程序重定向到登录页面。到目前为止一切都很好。
但是,在成功登录后,应用程序再次将我重定向到登录页面并且它不会创建任何会话,以便即使尝试直接访问URL(在URL栏中键入它),应用程序也会重定向到登录页面。
我必须要求登录才能访问它们。其他人,我可以访问没有身份验证。这些我不需要身份验证的URL工作正常(即没有要求登录并访问URL),但那些需要身份验证的URL要求登录,但在输入用户名和密码后,它就会被输入再次重定向到登录页面,我无法直接访问该网址。
我的configure()方法是:
// Those URL pattern I need authentication to access them.
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/gerenciar/**", "/admin/adicionar/**", "/admin/index.html", "/admin/").
authenticated().and().formLogin().loginPage("/admin/login.html").permitAll();
}
我不确定是否需要发布任何其他代码来澄清我的问题或帮助其他人回答我。如果是这样,请告诉我,以便我可以更新我的问题。
编辑1
一个问题:我想在antMatchers()方法参数中要求对这些URL进行身份验证:我是否需要编写" /admin/index.html"和" / admin /"?对于Spring Security来说它是一样的吗?
编辑2
网址我希望每个人都能访问:" /"和" / admin / resources / **"。在inside / admin / resources中,我有css和js,这就是为什么我希望每个人都能访问它们。这些网址不需要身份验证。
我需要人们对网址进行身份验证:" / admin / gerenciar / **"," / admin / adicionar / **"和" / admin /" (含蓄地说" /admin/index.html"当然)。
我现在的问题是:如何为其执行代码(在configure()方法内部?)
答案 0 :(得分:1)
我的理解是 -
任何人都可以访问/,admin / login.html和/ admin / resources / **, 但不是其他管理员网址?
我认为该方法应该是 -
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**", "/admin/login.html", "/admin/resources/**").permitAll()
.antMatchers("/admin/**", "/admin/gerenciar/**", "/admin/adicionar/**").
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/admin/login.html")
.permitAll();
}
答案 1 :(得分:0)
我发现一种解决方法可以提供预期的功能here,但可能有一个重要缺陷:Spring-boot在较早版本中默认使用的加密NoOpPasswordEncoder
现在被认为是不安全的。我想,该解决方案将强制执行该加密,因此对于学习目的或安全上下文来说还可以。
只需在密码字符串{noop}中添加它即可。
@Configuration
@EnableWebSecurity 公共类WebSecurityConfig扩展了WebSecurityConfigurerAdapter {
// create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}pass").roles("USER")
.and()
.withUser("admin").password("{noop}pass").roles("ADMIN");
}
我有兴趣阅读有关此内容的说明,这对我来说并不简单。
答案 2 :(得分:0)
对我有用。登录成功后,Spring安全性将重定向到“ /”,然后,我检查用户是否已通过身份验证,在这种情况下,将其重定向到我的仪表板页面。
@RequestMapping("/")
public String index(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken))
return "dashboard";
// if it is not authenticated, then go to the index...
// other things ...
return "index";
}