我们所有的假设条件是,已经安装配置好springMVC环境或SpringBoot加入了web包。 为了更直观地看到跳转流程,我们添加一些页面和演示代码说明thymeleaf
(1)在web包下新建SecurityController
@Controller
public class SecurityController {
@RequestMapping("/home")
public ModelAndView home(String msg) {
ModelAndView mv = new ModelAndView();
mv.setViewName("home");
mv.addObject("msg", msg);
return mv;
}
}
(2) 在templates下新建login.html,home.html,内容如下
// login.html
Login Page
// home.html
Home Page
Hello
其中login.html用作登录页面,Spring Security 只是默认post到/login的请求为登录请求,而并未指明具体的登录页面,所以我们需要自己配置登录页面。原理就是配置MVC实现Controller与view的自定义跳转,即我们只需要实现 WebMvcConfigurer配置类即可;(这里不使用"@{/login}",也可以直接使用"/login"或“login”)
(3) 在config包下创建WebMvcConfig继承WebMvcConfigurerAdapter,创建WebSecurityConfig继承WebSecurityConfigurerAdapter或者自己实现WebMvcConfigurer接口(接口部分实现自己希望覆盖的接口)
/*****WebMVC配置******/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 前面是url路径,后面是视图路径,添加thymeleaf后自动配置prefix为/templates,suffix为.html
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/home").setViewName("/home");
}
}
重点要说明的是:添加thymeleaf后自动配置prefix为/templates,suffix为.html
/*****WebSecurity配置******/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() //定义权限配置
.anyRequest().authenticated() //任何请求都必须经过认证才能访问
.and()
.formLogin() //定制登录表单
.loginPage("/login") //设置登录url-定制登录页面
.defaultSuccessUrl("/home") //设置登录成功默认跳转url
.permitAll() //允许任何人访问登录url
.and()
.logout().permitAll(); //允许任何人访问登出url
}
}
现在运行项目,Spring Security会自动生成一个用户放到内存中,用户名为user,密码会在项目启动时显示,直接访问http://localhost:8080/home将跳转到登录页面,输入用户名密码后就能看到home页面了(展示hello字样和注销按钮)
home页面:
点击注销后Spring Security将注销用户session并跳转到/login?logout,如果登录失败,比如用户名不存在、密码错误等情况,将跳转到/login?error
此时登录失败或注销后便可以显示相应的提示信息