项目开发记录3 Security结合数据库认证

选择依赖
web
sql driver
mybatis


锁定数据库版本5.1.27
加入druid-spring-boot-starter依赖1.1.10


配置数据库信息
application.properties


设置xml打包

src/main/java **/*.xml src/main/resources

创建表
user
id username password enabled locked

role
id name nameZh

user_role
id uid rid

menu
id pattern

menu_role
id mid rid

创建实体类
role{
int id;
string name;
string nameZh;
}
//省略getset方法

user
{
int id;
string username;
string password
boolean enabled;
boolean locked;
List roles;
}


package org.javaboy.securitydb.bean;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class User implements UserDetails {
    private Integer id;
    private String username;
    private String password;
    private Boolean enabled;
    private Boolean locked;
    private List<Role> roles;

//实现方法 实则为属性对应get方法
@Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

//实现剩余get set方法
//省略

实现mapper
@mapper

User loadUserbyUsername(String username);
List<role> getRolesById(Integer id);
<select id = "loadUserByUsername" resultType = "User">
	select * from user where username = #{username}
</select>

<select id = "getRolesById" resultType = "Role">
	select * from role where id in(
	select rid from user_role where uid = #{id}
)
</select>

实现service

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

        return user;
    }

实现service

@Autowired
    UserMapper userMapper;

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

        return user;

实现SecurityConfig

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

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


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

//角色继承
@Bean
RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    String hierarchy = "ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user";
    roleHierarchy.setHierarchy(hierarchy);
    return roleHierarchy;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值