配置验证
@Component public class CustomUserDetailsService implements UserDetailsService { @Autowired StaffMapper staffMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); //加密类, Staff staff = staffMapper.findByAccount(username); //从数据库中查询 Listlist = new ArrayList<>(); //拥有的权限 if(staff == null){ throw new UsernameNotFoundException("用户不存在"); }else { list.add(new SimpleGrantedAuthority(staff.getPower())); } org.springframework.security.core.userdetails.User security = new org.springframework.security.core.userdetails.User(staff.getStaffAccount(),bCryptPasswordEncoder.encode(staff.getStaffPassword()),list);//因为数据库中存的是名文所以password需要加密 return security; } }
继承配置类
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法级验证 public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomUserDetailsService customUserDetailsService; @Bean public PasswordEncoder passwordEncoder(){ // 使用BCrypt加密密码 return new BCryptPasswordEncoder(); } //配置自定义登入页面。如果注释掉将使用默认页面 @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/pages/login.html") //登入页面 .loginProcessingUrl("/login") //登入url 与登入表单中的action必须相同 .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/pages/main.html",true)//默认登入页面 true是当输入一个不存在的页面时,进入登入页面,登入后依然进入main.html .failureUrl("/login?error") //登入失败 .and() .csrf().disable(); //关闭csrf过滤器 http.logout() .logoutUrl("/logout") //登出url .logoutSuccessUrl("/login"); //登出成功url http.authorizeHttpRequests() .antMatchers("/pages/login.html").permitAll() //所有人都可以访问 .antMatchers("/pages/report.html").hasRole("MANAGER") //必须拥有MANAGER权限才可以访问。给予权限名时必须是ROLE_MANAGER才行 .anyRequest().authenticated(); //所有的访问都需要权限 http.headers().frameOptions().disable(); //在iframe中可以展示 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)