我是Spring Boot的新手,我有一个使用Spring Boot和Spring Security的小应用程序。成功登录后,页面将再次重定向到/ login。我不知道该如何解决。
成功登录后:
这是安全性配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/login").permitAll()//设置SpringSecurity对"/"和"/login"路径不拦截
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")//设置Spring Security的登录页面访问路径为/login
.defaultSuccessUrl("/chat")//登录成功后转向/chat路径
.permitAll()
.and()
.logout()
.permitAll();
}
/**
* 在内存中分别配置两个用户xin.luo和king.luo,密码和用户名一致,角色是USER
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("xin").password("xin").roles("USER")
.and()
.withUser("king").password("king").roles("USER");
}
/**
* /resources/static/目录下的静态资源文件,Spring Security不拦截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/static/**");
}
}
您需要什么行为?基本上,有两种选择:重定向到某个静态静态的知名位置(如)/index
,或重定向到最初请求的页面。两者都需要配置AuthenticationSuccessHandler
。您还可以使用/扩展现有的身份验证处理程序之一来完成一些基本任务。例如,请注意如何SimpleUrlAuthenticationSuccessHandler
用于重定向到最初请求的页面:
XML安全配置:
<http use-expressions="true">
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
...
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-success-handler-ref="refererAuthenticationSuccessHandler"
...
/>
<logout/>
</http>
<!-- Route users to their profiles and admins to the admin console: -->
<beans:bean id="authenticationSuccessHandler" class="a.b.c.AuthenticationSuccessHandler"/>
<!-- Route to the originally requested page -->
<beans:bean id="refererAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
<property name="useReferer" value="true"/>
</beans:bean>
范例AuthenticationSuccessHandler
:
public class AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
// Very simple (most probably broken) check if the user is ADMIN or USER
if (authentication.getAuthorities().stream().filter(a -> a.getAuthority().equals("USER")).findAny() != null){
redirectStrategy.sendRedirect(request, response, "/profile.html");
} else {
redirectStrategy.sendRedirect(request, response, "/admin.html");
}
clearAuthenticationAttributes(request);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句