Spring boot for Eclipse 开发指南第五节 自定义登陆页

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";  
    }  
}
相关文章
相关标签/搜索