Spring Boot 整合Spring Security
阿新 • • 發佈:2018-12-18
整合Spring Security
效果:訪問hello.html會被重定向到login.html,登入成功後,轉到hello,登入失敗,轉到error
一:新增依賴
<!-- spring security依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
二:配置SecurityConfig
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //所有訪問都需要驗證 .anyRequest().authenticated() .and() //自定義登入頁面 .formLogin().loginPage("/login") .loginProcessingUrl("/form") //失敗頁面 .failureUrl("/error") //登入成功頁面 .defaultSuccessUrl("/hello") .permitAll() .and() //關閉csrf .csrf().disable() ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() //自定義記憶體角色 .withUser("admin").password(passwordEncoder().encode("1")).roles("USER"); } }
三:頁面
login.hrml
<body> <form action="/form" method="POST"> <table> <tr> <td>使用者名稱:</td> <td><input typpe="text" name="username" value="admin"></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="password" value="1"> <td></td> <tr> <td colspan="2"><input type="submit" value="登入"></td> </tr> </table> </form> </body>