<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
package cn.stevekung.security;
import cn.stevekung.service.impl.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public CustomUserService customUserService(){
return new CustomUserService();
}
// 登入成功跳转URL 失败URL 默认登录页面
@Override
protected void configure(HttpSecurity http) throws Exception {
//路由策略和访问权限的简单配置
http
.formLogin() //启用默认登陆页面
.failureUrl("/login?error") //登陆失败返回URL:/login?error
.defaultSuccessUrl("/ayUser/test") //登陆成功跳转URL,这里调整到用户首页
.permitAll(); //登陆页面全部权限可访问
super.configure(http);
}
// 分配权限 配置内存用户
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserService()) // 判断角色权限
.passwordEncoder(new MyPasswordEncoder()); // 判断密码正确与否
// .inMemoryAuthentication()
// .passwordEncoder(new MyPasswordEncoder())
// .withUser("steve").password("123456").roles("ADMIN")
// .and()
// .withUser("gj").password("123456").roles("USER");
}
}
package cn.stevekung.security;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
// 决定密码如何编码
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
// 判断未编码的字符串与编码后的字符串是否匹配
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
DROP TABLE IF EXISTS `ay_role`;
CREATE TABLE `ay_role`(
`id` VARCHAR(255) DEFAULT NULL ,
`name` VARCHAR(255) DEFAULT NULL COMMENT '角色'
)ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT '角色表';
DROP TABLE IF EXISTS `ay_user_role_rel`;
CREATE TABLE `ay_user_role_rel`(
`user_id` VARCHAR(255) DEFAULT NULL ,
`role_id` VARCHAR(255) DEFAULT NULL
)ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT '用户角色关联表';
INSERT INTO ay_role VALUES ('1', 'ADMIN');
INSERT INTO ay_role VALUES ('2', 'USER');
INSERT INTO ay_user_role_rel (user_id, role_id) VALUES ('1','1');
INSERT INTO ay_user_role_rel (user_id, role_id) VALUES ('2','2');
package cn.stevekung.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "ay_role")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AyRole {
@Id
private String id;
private String name;
}
package cn.stevekung.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "ay_user_role_rel")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AyUserRoleRel {
@Id
private String userId;
private String roleId;
}
package cn.stevekung.repository;
import cn.stevekung.pojo.AyRole;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AyRoleRepository extends JpaRepository<AyRole, String> {
}
package cn.stevekung.repository;
import cn.stevekung.pojo.AyUserRoleRel;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AyUserRoleRelRepository extends JpaRepository<AyUserRoleRel, String> {
List<AyUserRoleRel> findByUserId(@Param("userId")String userID);
}
package cn.stevekung.service.impl;
import cn.stevekung.pojo.AyRole;
import cn.stevekung.repository.AyRoleRepository;
import cn.stevekung.service.AyRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AyRoleServiceImpl implements AyRoleService{
@Autowired
AyRoleRepository ayRoleRepository;
@Override
public AyRole find(String id) {
return ayRoleRepository.findById(id).get();
}
}
package cn.stevekung.service.impl;
import cn.stevekung.pojo.AyUserRoleRel;
import cn.stevekung.repository.AyUserRoleRelRepository;
import cn.stevekung.service.AyUserRoleRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AyUserRoleServiceImpl implements AyUserRoleRelService {
@Autowired
AyUserRoleRelRepository ayUserRoleRelRepository;
@Override
public List<AyUserRoleRel> findByUserId(String userId) {
return ayUserRoleRelRepository.findByUserId(userId);
}
}
@Service
@Transactional
public class AyUserServiceImpl implements AyUserService {
@Override
public AyUser findByUserName(String name) {
List<AyUser> ayUsers = findByName(name);
if(ayUsers == null && ayUsers.size() <= 0){
return null;
}
return ayUsers.get(0);
}
}
package cn.stevekung.service.impl;
import cn.stevekung.error.BusinessException;
import cn.stevekung.pojo.AyUser;
import cn.stevekung.pojo.AyUserRoleRel;
import cn.stevekung.service.AyRoleService;
import cn.stevekung.service.AyUserRoleRelService;
import cn.stevekung.service.AyUserService;
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.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class CustomUserService implements UserDetailsService {
@Autowired
AyUserService ayUserService;
@Autowired
AyUserRoleRelService ayUserRoleRelService;
@Autowired
AyRoleService ayRoleService;
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
AyUser ayUser = ayUserService.findByUserName(name);
if(ayUser == null){
throw new BusinessException("用户不存在");
}
//获取用户所有的关联角色
List<AyUserRoleRel> ayRoleList = ayUserRoleRelService.findByUserId(ayUser.getId());
List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
if(ayRoleList != null && ayRoleList.size() > 0){
for(AyUserRoleRel rel:ayRoleList){
//获取用户关联角色名称
String roleName = ayRoleService.find(rel.getRoleId()).getName();
authorityList.add(new SimpleGrantedAuthority(roleName));
}
}
return new User(ayUser.getName(), ayUser.getPassword(), authorityList);
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public CustomUserService customUserService(){
return new CustomUserService();
}
// 分配权限 配置内存用户
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserService()) // 判断角色权限
.passwordEncoder(new MyPasswordEncoder()); // 判断密码正确与否
// .inMemoryAuthentication()
// .passwordEncoder(new MyPasswordEncoder())
// .withUser("steve").password("123456").roles("ADMIN")
// .and()
// .withUser("gj").password("123456").roles("USER");
}
}
// 登入成功跳转URL 失败URL 默认登录页面
@Override
protected void configure(HttpSecurity http) throws Exception {
//路由策略和访问权限的简单配置
http
.authorizeRequests()
//要求有管理员的权限
.antMatchers("/shutdown").access("hasRole('ADMIN')")
.antMatchers("/**").permitAll()
.and()
.formLogin() //启用默认登陆页面
.failureUrl("/login?error") //登陆失败返回URL:/login?error
.defaultSuccessUrl("/ayUser/test") //登陆成功跳转URL,这里调整到用户首页
.permitAll(); //登陆页面全部权限可访问
super.configure(http);
}