Spring Security 简单使用记录

准备工作

  • 导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • @EnableWebSecurity 开启security认证拦截

基于内存配置信息

  • 继承 WebSecurityConfigurerAdapter,重写两个configure方法

  • 内存配置权限信息
  auth.inMemoryAuthentication().withUser("dream_admin").password("admin").authorities("addUser","showUser","delUser","updateUser");
     auth.inMemoryAuthentication().withUser("dream_add").password("add").authorities("addUser");
   auth.inMemoryAuthentication().withUser("dream_del").password("del").authorities("delUser");
       http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
or
       http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();

 

 

 

 

 

 

基于数据库配置信息

  • 实现  UserDetailsService 和 UserDetails
  • 重写 loadUserByUsername方法, 从数据库查询相应User信息
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1 query user according to username
        //2 query related permission
        //3 add permissions into security configration
        UserEntity userEntity = userMapper.findByUsername(username);
        if(null == userEntity){
            return null;
        }

        List<PermissionEntity> permissionEntityList = userMapper.findPermissionByUsername(username);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        permissionEntityList.forEach(permissionEntity -> {
            authorityList.add(new SimpleGrantedAuthority(permissionEntity.getPermissionTag()));
        });
        userEntity.setAuthorities(authorityList);
        return userEntity;
    }
  • 继承 WebSecurityConfigurerAdapter,重写两个configure方法
        auth.userDetailsService(memberUserDetailService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence password) {
                return MD5Util.encode((String) password);
            }

            @Override
            public boolean matches(CharSequence password, String encodePassword) {
                return encodePassword.equals(MD5Util.encode((String) password));
            }
        });
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.authorizeRequests();
        List<PermissionEntity> allPermission = permissionMapper.findAllPermission();
        allPermission.forEach(permissionEntity -> {
            expressionInterceptUrlRegistry.antMatchers(permissionEntity.getPermissionUrl()).hasAuthority(permissionEntity.getPermissionTag());
        });
        expressionInterceptUrlRegistry
                .antMatchers("/login").permitAll()
                //shutdown csrf
                .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();

配置相应状态路径跳转

  • 添加 ConfigurableServletWebServerFactory  配置
    @Bean
    public ConfigurableServletWebServerFactory  webServerFactory(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400,errorPage401,errorPage403,errorPage404,errorPage415,errorPage500);

        return factory;
    }
  • 编写对应controller层mapping
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值