SpringSecurity

Springboot整合SpringSecurity

1.引入依赖

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

2.配置类Config

继承WebSecurityConfigurerAdapter
因为我们会重载其中的configure方法,注意configure方法会有不同的参数,不同参数的configure方法的作用一般不同

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

void configure(AuthenticationManagerBuilder auth)
该方法用来提供认证用户
注释掉的部分是另一种引入认证用户的方法,在这里采用了从数据库中的方法。

   @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        String password = passwordEncoder.encode("qp");
//        auth.inMemoryAuthentication().withUser("qp").password(password).roles("admin");
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

控制访问部分
我们发现其方法名也是configure

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.exceptionHandling().accessDeniedPage("/unauth");
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccess").permitAll();
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/user/login")
                .defaultSuccessUrl("/test").permitAll()
                .and().authorizeRequests()
                .antMatchers("/user/register","/register.html","/comments/game/all")
                        .permitAll()
//                .antMatchers("/test").hasAuthority("users")
                .anyRequest().authenticated()
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60).userDetailsService(userDetailsService)
                .and().csrf().disable(); //关闭csrf防护
    }

设置组件

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

3.Service编写

导入usermapper

  @Autowired
    private UsersMapper usersMapper;

重载方法,将指定用户名的用户从数据库中读取出来,并为其绑定角色

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        QueryWrapper<Users> wrapper = new QueryWrapper();
        wrapper.eq("username",username);
        Users user = usersMapper.selectOne(wrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admins");
        return new User(user.getUsername(),
              user.getPassword(),auths);
    }

Controller中设置访问权限

在此处展示一种设置方法

    @ResponseBody
    @RequestMapping(value = "/test")
    @Secured({"ROLE_admins"})
    public Object testHello(HttpServletRequest request){
        return "OK";
    }

注意到这里是ROLE_admins和Service中对应
原因在于Security源码在使用这种方法进行权限判定时,有前缀ROLE_的判断

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值