spring boot 整合 spring security 之使用数据库验证

spring boot 整合 spring security 参见上一篇文章.

重写WebSecurityConfigurerAdapter中的configureGlobal方法

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(custProvider);
}

其中custProvider是AuthenticationProvider接口的一个实现类实例

实现AuthenticationProvider接口

@Component
public class CustAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustUserDetailsService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        CustUserDetails userDetials = (CustUserDetails) userService.loadUserByUsername(username);
        Collection authorities = userDetials.getAuthorities();
        return new UsernamePasswordAuthenticationToken(userDetials, password, authorities);
    }
    @Override
    public boolean supports(Class arg0) {
        return true;
    }

}

其中CustUserDetailsService是UserDetailsService接口的实现类;CustUserDetails是UserDetails接口的实现类

实现UserDetailsService接口

@Component
public class SnailUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        return new CustUserDetails();
    }
}

重写loadUserByUsername方法,实现依据用户名称从数据库中查找用户的罗辑,并返回UserDetails对象,这里为了简单我就直接创建了一个

实现UserDetails接口

public class CustUserDetails implements UserDetails {

    private static final long serialVersionUID = -1922135614793714181L;

    @Override
    public Collection getAuthorities() {
        boolean flag = false;
        if (flag) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList("");
        }
        StringBuilder commaBuilder = new StringBuilder();
        commaBuilder.append("SUPPER MANAGER");
        commaBuilder.append(",");
        commaBuilder.append("hello");
        commaBuilder.append(",");
        commaBuilder.append("view");
        return AuthorityUtils.commaSeparatedStringToAuthorityList(commaBuilder.toString());
    }
    @Override
    public String getPassword() {
        return "123456";
    }
    @Override
    public String getUsername() {
        return "administrator";
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }
}

主要是实现getAuthorities方法根据用户将用户所有的权限查询出来并返回Collection

你可能感兴趣的:(基础知识,学习笔记,框架,spring-boot)