上一篇文章 [Spring Cloud] - Spring Security实践(一)- 基本概念及实践 中, 我们已经实现了基本的security鉴权和认证. 下面会在此基础上加一些自定义的配置.
Spring security默认使用/login方法跳转到登录界面, 我们替换login页面,只需将/login指向的界面换成自己的即可.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
@Controller public class Login { @GetMapping("/login") private String loginController(){ return "login"; } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example </title> </head> <body> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <form th:action="@{/login}" method="post"> <div><label> User Name : <input type="text" name="username"/> </label></div> <div><label> Password: <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign In"/></div> </form> </body> </html>
Spring security框架会拦截login的post请求
@EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("root").password(new BCryptPasswordEncoder().encode("1234")).roles("ADMIN") .and() .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // .antMatchers("/", "/user").permitAll() .antMatchers("/user").hasRole("USER") .antMatchers("/admin").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } }