如果用户无权访问 Spring 安全性中的特定控制器或 URL,则需要提示登录页面.如何实现?



我正在使用spring-boot,spring-security和JSP。如果我单击一个按钮,如果用户已登录,它应该转到控制器。否则,它应该首先要求用户登录,然后返回该页面。简而言之,如果用户已登录,他应该会看到该页面。我怎样才能做到这一点?

我认为可能会使用过滤器/反匹配器,但我想知道用户在登录后将如何返回该特定页面/控制器?

尝试使用类似的方式来允许用户访问某些页面,然后相应地设置默认的成功 URL。 你可以有一个主页,就像我在这里用"/"表示的那样,一旦用户登录,他们就会被重定向到你的/welcome页面。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
// Public access to login, landing, and error pages
http.authorizeRequests().antMatchers("/", "/login", "/errorpage").permitAll();

// Static resource permissions
http.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/images/**", "/webfonts/**", "/js/**", "/webjars/**", "/messages/**")
.permitAll();
// Login specifications
http.formLogin().loginPage("/login").defaultSuccessUrl("/welcome", true);
// Logout specifications
http
.logout()
.deleteCookies("remove")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll();
}
}

WebSecurityConfigurerAdapter实现中,您需要通知formLogin并指定loginPage
这足以让 Spring 以这种方式使用端点/login

如果您尝试访问未登录的页面,例如/profile,您将被重定向到/login,登录后,您将被重定向到/profile

在此示例中,您有 3 个无需身份验证即可访问的页面/ ,/homeand/info'

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/info" ).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
...
}

最新更新