Spring security安全框架

Spring security安全框架

1.添加依赖
      //主要加这个依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>   
    
    //这个依赖是用于在前端判断提示的,需要在页面导入
     <xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
2.配置SecurityConfig
//拦截后跳到登陆,登陆成功后跳到首页
@Configuration
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserServiceImp userServiceImp;
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll() //首页所有人可以访问
                .antMatchers("/level1/**").hasRole("vip1") // /level1/**只有vip1才能访问
                .antMatchers("/level2/**").hasRole("vip2") // /level2/**只有vip2才能访问
                .antMatchers("/level3/**").hasRole("vip3"); // /level3/**只有vip3才能访问
        //没有权限默认跳转到登陆页面,需要开启登陆页面
        //http.formLogin();//系统自带的login页面
        //设置默认跳转的登陆页面,登陆成功后跳转到首页  这里的tologin是和from里面对应的  username password是前端用户输入的name
        http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("password");
        http.csrf().disable();//关闭csrf功能,如果不关的话 注销可能会有提示
        //注销  注销成功后跳到首页
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("rememberMe");
    }
   //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userServiceImp);
    }
    //加密方法
    @Bean
    public BCryptPasswordEncoder bcryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
3.UserServiceImp实现UserDetailsService
@Service
public class UserServiceImp implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.querUserByName(username);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //因为UserDetails返回值得第三个参数是个Collection集合,所以必须保存在list集合里
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //Spring security从数据库中添加权限必须要加前缀ROLE_,不然读取不到
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getPerms()));
        //对密码进行加密
        String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
        //将加密了的密码保存到user中
        user.setPassword(encodedPassword);     
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
4.前端页面
<!--判断用户是否登录,如果未登录,就显示登录按钮-->
                <div sec:authorize="!isAuthenticated()">
                <a class="item" th:href="@{/tologin}">
                    <i class="address card icon"></i> 登录
                </a>
                </div>
<!--如果已经登录,就显示用户名按钮,注销按钮-->
<div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用户名:<span sec:authentication="name"></span>
                    </a>
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>
            </div>
<!--如果已经登录,且用户有vip1的权限,那么就显示以下内容-->
<div class="column" sec:authorize="hasRole('vip1')">
        vip1用户才能看得见    
 </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值