一、使用formLogin模式进行鉴权
在configure(HttpSecurity http)方法里写入如下代码
http.csrf().disable() .formLogin() .loginPage("/login.html")//设置登录页,该页面放在public目录下 .loginProcessingUrl("/login")//设置登录请求地址,默认就是login .defaultSuccessUrl("/index")//设置登录成功后跳转地址 .usernameParameter("uname")//配置用户名参数,默认是username .passwordParameter("pword")//配置密码参数,默认是password .and() .authorizeRequests() .antMatchers("/login.html","/login").permitAll()//配置无需认证即可访问的请求 .antMatchers("/biz1","/biz2").hasAnyAuthority("ROLE_user","ROLE_admin")//配置需要权限才能访问的请求 .antMatchers("/syslog","/sysuser").hasAnyAuthority("ROLE_admin") .anyRequest().authenticated();//配置其他的所有请求需要认证
然后重写另外两个configure方法
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //从内存里获取用户数据 auth.inMemoryAuthentication() //配置用户信息 .withUser("user").authorities("ROLE_user").password(new BCryptPasswordEncoder().encode("1")) .and() //配置管理员信息 .withUser("admin").authorities("ROLE_user","ROLE_admin").password(new BCryptPasswordEncoder().encode("1")) .and() //密码均采用BCrypt加密方式 .passwordEncoder(new BCryptPasswordEncoder()); } @Override public void configure(WebSecurity web) throws Exception { //放行所有静态资源 web.ignoring() .antMatchers("/css/**","/font/**","/js/**","/img/**"); }
自定义表单代码:
<form action="/login" method="post"> <span>用户名称</span><input type="text" name="uname" id="username"/> <br> <span>用户密码</span><input type="password" name="pword" id="password"/> <br> <span>验证码</span><input type="text" name="captchaCode" id="captchaCode"/> <input type="submit" value="登陆"> <label><input type="checkbox" name="remember-me" id="remember-me"/>记住密码</label> </form>
记住我功能在configure(HttpSecurity http)方法里加入:
//开启记住我功能,默认参数是remember-me http.rememberMe();
勾选记住我登录成功后,就会有一个remember-me的cookie
