1. Spring Security 配置類css
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("customUserDetailService") private UserDetailsService userDetailsService; /**定義認證用戶信息獲取來源,密碼校驗規則等*/ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("shili").password("zzz123").roles("ADMIN"); //auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); //auth.userDetailsService(userDetailsService); } /**定義安全策略*/ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()//配置安全策略 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')") .antMatchers("/css/**","/js/**","/img/**").permitAll()//定義/請求不須要驗證 .anyRequest().authenticated()//其他的全部請求都須要驗證 .and() .logout() .logoutSuccessUrl("/login?logout") .permitAll()//定義logout不須要驗證 .and() .formLogin() .loginPage("/login")//自定義 login頁面 .usernameParameter("user-name") //對應頁面的username .passwordParameter("pwd") //對應頁面的 password .defaultSuccessUrl("/home")//登陸成功頁 .failureUrl("/login?error") .permitAll() .and() .csrf().disable(); } @Bean public BCryptPasswordEncoder passwordEncoder(){ BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); return encoder; }
2. login.htmlhtml
<h1>Spring Security 瀋陽中航安科科學技術有限公司 登陸頁</h1> <form name='loginForm' action="/login" method='POST'> <span style="color:red">${error!}<span> <span style="color:blue">${msg!}<span> <table> <tr> <td>名:</td> <td><input type='text' name='user-name' /></td> </tr> <tr> <td>mima:</td> <td><input type='password' name='pwd' /></td> </tr> <tr> <td colspan='2'> <input type="submit" value="提交" /> </td> </tr> </table> </form>
3. LoginControllerjava
@Controller public class Login { @RequestMapping("/login") public String login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout, Map<String,Object> map) { if (error != null) { map.put("error", "不正確的用戶名和密碼"); } if (logout != null) { map.put("msg", "你已經成功退出"); } return "login"; } }