boke例子:用户登录

boke例子:用户登录

1.首先创建user表,authority表(角色),user_authority,表(用户角色表)

Authority实体类,需要继承:GrantedAuthority类,

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.springframework.security.core.GrantedAuthority;

/**
 * 权限
 * @author 
 *
 */
@Entity
public class Authority implements GrantedAuthority {


	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	
	@Column(nullable=false, length=20)
	private String name;
	
		
	
	@Override
	public String getAuthority() {
		// TODO Auto-generated method stub
		return name;
	}


	public Long getId() {
		return id;
	}


	public void setId(Long id) {
		this.id = id;
	}
	

	public void setName(String name) {
		this.name = name;
	}

	
	
}

  

 

User类.需要继承security的UserDetails类:

并复写:isAccountNonExpired,isAccountNonLocked,isCredentialsNonExpired, isEnabled返回true值

同事复写:

@Override
	public Collection getAuthorities() {		
		//需将 List 转成 List,否则前端拿不到角色列表名称
		List simpleGrantedAuthorities = new ArrayList<>();
		for(GrantedAuthority authority: this.authorities)
		{
			simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
		}
		return simpleGrantedAuthorities;		
	}

  

如下:

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
public class User implements UserDetails,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//private AtomicLong atomicLong = new AtomicLong();
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	@NotEmpty(message="姓名不能为空")
	@Size(min=2, max=20)
	@Column(nullable=false, length=20)
	private String name;
	
	@NotEmpty(message="邮箱不能为空")
	@Size(max=50)
	@Email(message="邮箱格式不正确")
	@Column(nullable=false, length=50, unique=true)
	private String email;	
	
	@NotEmpty(message="账号不能为空")
	@Size(min=3, max=20)
	@Column(nullable=false, length=20, unique=true)
	private String username;
	
	@NotEmpty(message="密码不能为空")
	@Size(min=3, max=20)
	@Column(nullable=false, length=20)
	private String password;
	
	@Column(length=200)
	private String avatar;
	
	
	//权限多对多	
	@ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
	@JoinTable(name = "user_authority", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), 
		inverseJoinColumns = @JoinColumn(name = "authority_id", referencedColumnName = "id"))
	private List authorities;
	
	
	

	public User() {
		
	}

	public User(Long id, String name, String email, String username, String password) {	
		this.id = id;
		this.name = name;
		this.email = email;
		this.username = username;		
		this.password = password;
	}	
	
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAvatar() {
		return avatar;
	}

	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + ", username=" + username + "]";
	}

	@Override
	public Collection getAuthorities() {		
		//需将 List 转成 List,否则前端拿不到角色列表名称
		List simpleGrantedAuthorities = new ArrayList<>();
		for(GrantedAuthority authority: this.authorities)
		{
			simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
		}
		return simpleGrantedAuthorities;		
	}
	
	public void setAuthorities(List authorities) {
		this.authorities = authorities;
	}
	
	
	

	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}

	
	
	
	
}

  

同事创建user的userservice及userserviceImpl实现类,serviceImple继承userService和security的UserDetailsService

UserService:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.muyang.boke2.entity.User;

/**
 * 用户服务接口
 * @author feeyo
 *
 */
public interface UserService {

	/**
	 * 保持用户
	 * @param user
	 * @return
	 */
	User saveOrUpdateUser(User user);
	
	/**
	 * 注册用户
	 * @param user
	 * @return
	 */
	User registerUser(User user);
	
	/**
	 * 删除用户
	 * @param id
	 */
	void removeUser(Long id);
	
	/**
	 * 根据id查找用户
	 * @param id
	 * @return
	 */
	User findById(Long id);
	
	/**
	 * 根据用户的姓名分页查找用户
	 * @param name
	 * @param pageable
	 * @return
	 */
	Page listUsersByName(String name, Pageable pageable);
	
	/**
	 * 按分页查找数据
	 * @param pageable
	 * @return
	 */
	Page findAll(Pageable pageable);
}

  

UserServiceImpl:

继承security的UserDetailsService ,复写loadUserByUsername方法

/**
 * 用户服务接口实现
 * @author feeyo
 *
 */
@Service
public class UserServiceImpl implements UserService, UserDetailsService {

	@Autowired
	UserRepository userRepository;
	
	@Transactional
	@Override
	public User saveOrUpdateUser(User user) {
		// TODO Auto-generated method stub
		return userRepository.save(user);
	}

	@Transactional
	@Override
	public User registerUser(User user) {
		// TODO Auto-generated method stub
		return userRepository.save(user);
	}

	@Transactional
	@Override
	public void removeUser(Long id) {
		// TODO Auto-generated method stub
		userRepository.delete(id);
	}

	@Override
	public User findById(Long id) {
		// TODO Auto-generated method stub
		return userRepository.findOne(id);
	}

	@Override
	public Page listUsersByName(String name, Pageable pageable) {
		// TODO Auto-generated method stub
		name = "%" + name + "%";
		Page users = userRepository.findByNameLike(name, pageable);
		return users;
	}

	@Override
	public Page findAll(Pageable pageable) {
		// TODO Auto-generated method stub
		
		Page users = userRepository.findAll(pageable);
		
		return users;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		return userRepository.findByUsername(username);
	}

}

  

SecurityConfig网站全局配置/登录配置

@EnableWebSecurity
//启用全局post安全方法设置
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	private static final String key = "muyang.my";
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	
	/**
	 * 加密方法
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder()
	{
		return new BCryptPasswordEncoder();
		
	}
	
	@Bean
	public AuthenticationProvider authenticationProvider() {
		//从数据库获取信息
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
		authenticationProvider.setUserDetailsService(userDetailsService);
		//密码加密方式
		authenticationProvider.setPasswordEncoder(passwordEncoder());
		return authenticationProvider;
		
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(http);
		//关闭csrf验证:跨站攻击
		//http.csrf().disable();
		//权限设置
		http.authorizeRequests()     //定义那些url需要保护,哪些不需要保护
		.antMatchers("/static/**").permitAll()  //都可以访问
		.antMatchers("/user/**").hasRole("ADMIN") //需要登陆才能访问
		.and()		
		.headers().frameOptions().disable() //解决js跨站把x-frame-options disable即可
		.and()
		.formLogin() //基于FORM表单登陆验证
		.loginPage("/login").failureUrl("/login-error") //自定义登陆界面//自定义登陆错误页面
		.and().rememberMe().key(key) //记住我
		.and().exceptionHandling().accessDeniedPage("/403");  // 处理异常,拒绝访问就重定向到 403 页面
	}

	
	
	/**
	 * 认证信息管理
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public  void configureGlobal(AuthenticationManagerBuilder  auth) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(auth);
		//auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
		auth.userDetailsService(userDetailsService);
		auth.authenticationProvider(authenticationProvider());
	}

	
	/**
	 * 自动加载security-taglibs
	 * @return
	 */
	    @Bean
	    @ConditionalOnMissingBean(ClassPathTldsLoader.class)
	    public ClassPathTldsLoader classPathTldsLoader(){
	        return new ClassPathTldsLoader();
	    }
	
	
}

  

 

你可能感兴趣的:(boke例子:用户登录)