Spring Boot 集成 Spring Security 使用
创建时间:2018-05-19  访问量:12736  6  2

Spring Boot 集成 Spring Security 使用

UserDetailsService.java

package com.zxstrive.fight.sys.extend.security;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.zxstrive.fight.app.dao.jpa.UserRepo;
import com.zxstrive.fight.app.entity.jpa.UserEntity;
import com.zxstrive.fight.sys.utils.StringUtils;

public class CustomUserDetailsService implements UserDetailsService {
	
    //Jpa Repository
	@Autowired
	private UserRepo userRepo;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		UserDetailsBean user = new UserDetailsBean();
		List<UserEntity> users = userRepo.findByLoginName(userName);
		if(users != null && users.size() == 1) {
			user.setUser(users.get(0));
		}
		List<GrantedAuthority> grants = new ArrayList<GrantedAuthority>();
		grants.add(new SimpleGrantedAuthority("ROLE_USER"));
		user.setAuthorities(grants);
		return user;
	}

}

loadUserByUsername方法是通过用户名查找用户实体。