spring security入门学习(二)

2022-02-08  本文已影响0人  dylancc

1、基于数据库的认证(Mybstis)

数据库来源(用户密码均为123)

user表 role表

创建User实现UserDetails接口

public class User implements UserDetails {
  .......
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        return authorities;
    }
}

UserService实现UserDetailsService

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在!");
        }
        user.setRoles(userMapper.getUserRolesById(user.getId()));
        return user;
    }
}

完善UserMapper

@Mapper
public interface UserMapper {
    @ResultType(User.class)
    @Select("select * from user where username=#{username}")
    User loadUserByUsername(String username);

    @ResultType(Role.class)
    @Select("select * from role where id in (select rid from user_role where uid=#{id})")
    List<Role> getUserRolesById(Integer id);
}

配置SecurityConfig(root有dba、admin权限,admin具有admin权限,sang拥有user权限)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/abd/**").hasRole("dba")
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .csrf().disable();
    }
}

角色继承 (dba>admin>user使用‘\n’分隔关系)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Bean
    RoleHierarchy roleHierarchy(){
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        String hierarchy="ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user";
        roleHierarchy.setHierarchy(hierarchy);
        return roleHierarchy;
    }
}

上一篇下一篇

猜你喜欢

热点阅读