SpringSecurity学习日记 二

准备数据库

users 用户表

在这里插入图片描述
role 角色表
在这里插入图片描述
注意: password必须是加密形式,在测试中可以使用以下代码获得加密后的字符串

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode("password"));
// 得到类似结果
//  $2a$10$TlXkY79VCDieFjFRceAvDeiuyBpTUIOzx5HvuoCTUmIjLs5qoxFN. 

创建实体类并实现SpringSecurity接口

User实体类实现UserDetails 接口

public class User implements UserDetails {
    private String username;
    private String password;
    private String name;
    private String identity;
    List<UserRolo> roles = new ArrayList<>();
	
	// get set 方法
    
    @Override
    public boolean isAccountNonExpired() {  //判断用户是否过期,true未过期
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {  //判断用户是否锁定,true未锁定
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() { //判断凭据是否过期,true未过期
        return true;
    }

    @Override
    public boolean isEnabled() {	判断账户是否启用,true启动
        return true;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() { //获取权限列表
        return roles;
    }
}

Role实体类实现GrantedAuthority 接口

public class UserRolo implements GrantedAuthority {
	private int id;
    private String rolename;
    private String roledesc;
    private int uid;
    
	//get set 方法
	
	@Override
    public String getAuthority() { //GrantedAuthority 接口方法,用以返回角色名称字段
        return rolename;
    }

}

创建service 以及mapper

service 继承 UserDetailsService


public interface UserService extends UserDetailsService {

}

serviceImpl


@Service
class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.getUser(s); //查询用户
        return user;
    }
}

Mybatis Mapper

@Component
@Mapper
public interface UserMapper {

    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id=true,column="id",property="id"),
            @Result(column="username",property="username"),
            @Result(column="password",property="password"),
            @Result(column="id",property="roles",
                    many=@Many(select="com.tangye.springsecurity.mapper.UserMapper.getRoleList",fetchType= FetchType.EAGER))
    })
    User getUser(String username);

    @Select("select * from role where uid=#{id}")
    List<UserRolo> getRoleList(int id);

}

修改SpringSecurity 配置类

@Configuration
public class WebSecutityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .defaultSuccessUrl("/admin")
                .and()
                .authorizeRequests()
                .antMatchers("/admin").hasAuthority("admin")
                .antMatchers("/user").hasAuthority("user")
                .anyRequest().authenticated();
    }
}

启动测试

访问localhost:8080
在这里插入图片描述
以数据库中admin用户登录
在这里插入图片描述
在这里插入图片描述
发现只能访问admin页面 , 其他角色类型同理

以上便完成了一个简答的通过数据库动态认证

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值