1、在继承了WebSecurityConfigurerAdapter的配置类中配置
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin() /* 自定义自己编写的登录界面 */
.loginPage("/login") /* 登录页面设置 */
.loginProcessingUrl("/user/login") /* 登录访问路径 */
.defaultSuccessUrl("/success").permitAll() /* 登陆成功后跳转路径 */
.and().authorizeRequests() /* 指定哪些url可以访问,那些不能访问 */
.antMatchers("/test/index","/user/login").permitAll() /* 设置那些路径不需要认证可以访问 */
.anyRequest().authenticated() /* 所有请求都可以访问 */
.and().csrf().disable(); /* 关闭csrf防护 */
//用户注销
httpSecurity.logout()
.logoutUrl("/logout") /* 注销访问路劲 */
.logoutSuccessUrl("/test/index").permitAll(); /* 注销成功跳转路径 */
}
2、登陆界面与控制器设置
控制器
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("success")
public String success(){
return "success";
}
}
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/hello")
@ResponseBody
public String hello(@AuthenticationPrincipal UserDetails users){
/* 认证之后通过UserDetails获取表单参数 */
return "hello "+users.getUsername();
}
}
登录界面:/login
<body>
<h1>my login page</h1>
<!-- action要与配置中的登录访问路径一致 -->
<form action="/user/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
登入成功跳转页面:/logout
<body>
<h1>登入成功</h1>
<a href="/logout">注销</a>
</body>
3、运行效果