简介
Spring Security 是一款强大可定制的用于认证和授权的框架,为Spring项目提供安全保护。
在springBoot项目中添加springSecurity依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@TableName("xxx") @Data public class BzAdmin implements UserDetails { private int id; private String username; private String password; @TableLogic(value = "0",delval = "1") private int status = 0; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
2.修改数据库的数据 密码添加前缀noop代表不加密校验
3.写业务类
@Service public class BzAdminService extends ServiceImpl<BzAdminMapper,BzAdmin> implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { BzAdmin username = getOne(new QueryWrapper<BzAdmin>() .eq("username", s)); if (username==null){ throw new UsernameNotFoundException("用户不存在"); } return username; } }
@EnableWebSecurity @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private BzAdminService bzAdminService; @Override protected void configure(AuthenticationManagerBuilder auth)throws Exception{ //声明使用bzAdminService auth.userDetailsService(bzAdminService); } @Override protected void configure(HttpSecurity http) throws Exception { /** * authorizition 授权 * 在shiro和SpringSecurity中 所有以Author开头的单词都和授权业务有关系 * * authorizeRequests 配置拦截规则 * antMatchers 配置路径 * permitAll 不拦截 */ http.authorizeRequests() // 配置不拦截 .antMatchers("/admin/**","/img/**","/css/**","/js/**","/ztree/**","/login.jsp","/login","/layui/**") .permitAll() // 拦截所有 配置一般不会使用/** 而是独立配置 // anyRequest 代表所有路径 .anyRequest() .authenticated(); /** * 自定义登录页面 * * formLogin() 代表表单登录 * loginPage 自定义登录页面 * loginProcessingUrl 定义登录方法的地址 /login就是SpringSecurity中的认证方法 * successForwardUrl 登录成功后的地址 * failureForwardUrl 登录失败后的地址 */ http.formLogin() .loginPage("/login.jsp") .successForwardUrl("/main.jsp") .failureForwardUrl("/login.jsp") .loginProcessingUrl("/login") .and() .csrf() .disable() ; // html iframe标签引用二级页面 会被默认拦截 // 可以配置不拦截 http.headers().frameOptions().disable(); } }
5.Html
<html> <head> </head> <body class="layui-layout-login"> <form class="layui-form" action="/login" method="post"> <input name="username" id="username"> <input name="password" id="password" > <button type="submit" </button> </form> </body> </html>