/* 认证 :: 什么样的账号和密码是什么样的角色 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 什么账号,什么密码,是什么角色 auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("ADMIN") .and().withUser("zhangsan").password("{noop}123").roles("ZS") .and().withUser("lisi").password("{noop666}").roles("LS"); } /* 授权:: 什么样的角色能够访问什么样的地址 1. 先写什么请求是免登录直接放行的请求 2. 再写具体什么请求要求要有什么角色才能访问 3. 剩下的请求,全部都要登录才能访问 */ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()// .antMatchers( "/show01","/login.html" , "/register.html" , "/**/*.css").permitAll() // 免登录直接放行 .antMatchers("/show02").hasRole("ADMIN") // 只有admin能访问 /show02 .antMatchers("/show03").hasAnyRole("ZS","LS") // ZS 或者 LS 角色都能访问 /show03 .anyRequest().authenticated()// 剩下的请求地址,必须要登录才能访问! .and().formLogin() .loginPage("/login.html") // 登录的页面是什么 .loginProcessingUrl("/login") //执行登录的请求地址是哪个 .usernameParameter("username") //用户名的参数名是什么 .passwordParameter("password") //密码的参数名是什么 .defaultSuccessUrl("/index.html" , true) //登录成功之后,去到哪个页面 .failureForwardUrl("/login.html")// 登录失败之后,取到哪个页面 .and().csrf().disable() // 用来禁用 csrf [跨站请求伪造] .logout() // 用来配置退出登录 .logoutUrl("/logout") //退出登录的地址什么 .logoutSuccessUrl("/login.html"); // 退出登录成功,打开什么地址 //捕捉403的异常: http.exceptionHandling().accessDeniedHandler( (request,response,exception)->{ response.setContentType("text/html;charset=utf-8"); response.getWriter().write("权限不足,禁止访问!"); // {code:0, msg:"权限不足,禁止访问" , data:null} }); }