2018年3月5日 | Leave a comment 问题: 解决: demo 定制 UserDetailsService package demo.securityud; import demo.securityud.entity.Role; import demo.securityud.entity.User; import demo.securityud.repository.RoleRepo; import demo.securityud.repository.UserRepo; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @Component public class CustomeUserDetailsService implements UserDetailsService { @Autowired UserRepo userRepo; @Autowired RoleRepo roleRepo; public static class CustomeAuthority implements GrantedAuthority { private final String authority; public CustomeAuthority(String authority) { this.authority = authority; } @Override public String getAuthority() { return authority; } @Override public String toString() { return "CustomeAuthority{" + "authority=" + authority + '}'; } } public static class CustomeUserDetails implements UserDetails { private final User user; private final List<Role> roleList; public CustomeUserDetails(User user1, List<Role> roleList) { this.user = user1; this.roleList = roleList; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { final List<String> authList = new ArrayList<>(); if (this.roleList != null) { for (Role r : roleList) { final String auth = r.getAuthrities(); if (!StringUtils.isEmpty(auth)) { final String[] auths = auth.split(","); for (String s : auths) { final String ts = s.trim(); if (!StringUtils.isEmpty(ts) && !authList.contains(ts)) { authList.add(ts); } } } } } final List<GrantedAuthority> ret = authList.stream().map(auth -> new CustomeAuthority(auth)).collect(Collectors.toList()); return ret; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return user.getStatus() == 1; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return user.getStatus() == 1; } } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { final User user = userRepo.getByUsername(username); if (user == null) { throw new UsernameNotFoundException("username:" + username); } final List<Role> roleList = roleRepo.findByUserId(user.getId()); CustomeUserDetails ret = new CustomeUserDetails(user, roleList); return ret; } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 package demo.securityud; import demo.securityud.entity.Role;import demo.securityud.entity.User;import demo.securityud.repository.RoleRepo;import demo.securityud.repository.UserRepo;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.stream.Collectors;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils; @Componentpublic class CustomeUserDetailsService implements UserDetailsService { @Autowired UserRepo userRepo; @Autowired RoleRepo roleRepo; public static class CustomeAuthority implements GrantedAuthority { private final String authority; public CustomeAuthority(String authority) { this.authority = authority; } @Override public String getAuthority() { return authority; } @Override public String toString() { return "CustomeAuthority{" + "authority=" + authority + '}'; } } public static class CustomeUserDetails implements UserDetails { private final User user; private final List<Role> roleList; public CustomeUserDetails(User user1, List<Role> roleList) { this.user = user1; this.roleList = roleList; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { final List<String> authList = new ArrayList<>(); if (this.roleList != null) { for (Role r : roleList) { final String auth = r.getAuthrities(); if (!StringUtils.isEmpty(auth)) { final String[] auths = auth.split(","); for (String s : auths) { final String ts = s.trim(); if (!StringUtils.isEmpty(ts) && !authList.contains(ts)) { authList.add(ts); } } } } } final List<GrantedAuthority> ret = authList.stream().map(auth -> new CustomeAuthority(auth)).collect(Collectors.toList()); return ret; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return user.getStatus() == 1; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return user.getStatus() == 1; } } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { final User user = userRepo.getByUsername(username); if (user == null) { throw new UsernameNotFoundException("username:" + username); } final List<Role> roleList = roleRepo.findByUserId(user.getId()); CustomeUserDetails ret = new CustomeUserDetails(user, roleList); return ret; } } package demo.securityud; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().ignoringAntMatchers("/logout") .and().logout().invalidateHttpSession(true) .and() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/user").authenticated() .and().formLogin().permitAll() .and().logout().permitAll(); } } 1234567891011121314151617181920212223 package demo.securityud; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().ignoringAntMatchers("/logout") .and().logout().invalidateHttpSession(true) .and() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/user").authenticated() .and().formLogin().permitAll() .and().logout().permitAll(); }} package demo.securityud; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; @Component public class SHA256PasswordEncoder implements PasswordEncoder { private static final Logger LOG = Logger.getLogger(SHA256PasswordEncoder.class.getName()); @Override public String encode(CharSequence rawPassword) { final String ret = DigestUtils.sha256Hex(((String) rawPassword)); return ret; } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { final String ep = encode(rawPassword); LOG.log(Level.INFO, "rawPassword: {0}\t ep:{1}\t encodedPassword:{2}", new Object[]{rawPassword, ep, encodedPassword}); return Objects.equals(encodedPassword, ep); } } 12345678910111213141516171819202122232425262728 package demo.securityud; import java.util.Objects;import java.util.logging.Level;import java.util.logging.Logger;import org.apache.commons.codec.digest.DigestUtils;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Component; @Componentpublic class SHA256PasswordEncoder implements PasswordEncoder { private static final Logger LOG = Logger.getLogger(SHA256PasswordEncoder.class.getName()); @Override public String encode(CharSequence rawPassword) { final String ret = DigestUtils.sha256Hex(((String) rawPassword)); return ret; } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { final String ep = encode(rawPassword); LOG.log(Level.INFO, "rawPassword: {0}\t ep:{1}\t encodedPassword:{2}", new Object[]{rawPassword, ep, encodedPassword}); return Objects.equals(encodedPassword, ep); } } 参考: