Java开发学习.Day14
基于Springboot实现 shiro权限管理+springcloud eureka
本文内容是基于Java开发学习.Day13内容上所实现的
shiro权限管理
代码实现
创建两个新的实体类Permission和Role,用于配置用户角色,以及角色对应权限
@Entity
@Table(name = "t_permission")
public class Permission implements Serializable {
private static final long serialVersionUID = 6969178802824371390L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增
private Long id;
private String name;
private String code;
private String description;
public static long getSerialVersionUID() {
return serialVersionUID;
}
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@Entity
@Table(name = "t_role")
public class Role implements Serializable {
private static final long serialVersionUID = -1513987909228269210L;//序列id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增
private Long id;
private String name;
private String description;
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>(0);
@ManyToMany(fetch = FetchType.EAGER)
private Set<Permission> permissions = new HashSet<>(0);
public static long getSerialVersionUID() {
return serialVersionUID;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Set<Permission> getPermissions() {
return permissions;
}
public void setPermissions(Set<Permission> permissions) {
this.permissions = permissions;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", users=" + users +
", permissions=" + permissions +
'}';
}
}
创建newsRealm类,用于用户认证和授权
public class NewsRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
public void setName(String name){setName("nameRealm");}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken)authenticationToken;
String username = upToken.getUsername();
String password = new String(upToken.getPassword());
User user = userService.checkUsers(username,password);
if(user != null){
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
}
return null;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取用户认证信息
User user = (User)principalCollection.getPrimaryPrincipal();
//构造认证数据
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<Role> roles = user.getRoles();
for(Role role:roles){
//添加角色信息
info.addRole(role.getName());
for(Permission permission:role.getPermissions()){
info.addStringPermission(permission.getCode());
}
}
return info;
}
}
创建ShiroConfiguration,对shiro进行配置,设置对应权限
@Configuration
public class ShiroConfiguration {
//创建realm
@Bean
public NewsRealm getRealm(){
return new NewsRealm();
}
//创建安全管理器
@Bean
public SecurityManager securityManager(NewsRealm realm){
//使用默认的安全管理器
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager((realm));
//将自定义realm交给安全管理器同意调度管理
return securityManager;
}
//配置shiro过滤器工厂
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//通用配置
shiroFilterFactoryBean.setLoginUrl("/admin");
shiroFilterFactoryBean.setUnauthorizedUrl("/admin");
/**
* key:请求路径
* value:过滤器类型
*/
Map<String,String> filterMap=new LinkedHashMap<>();
filterMap.put("/admin/types","perms[user-types]");
filterMap.put("/admin/news","perms[user-news]");
filterMap.put("/admin/tags","perms[user-tags]");
filterMap.put("/admin/login","anon");
filterMap.put("/admin/**","authc");
System.out.println(filterMap);
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
}
// //开启shiro注解支持
// @Bean
// public SimpleMappingExceptionResolver resolver() {
//
// SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
//
// Properties properties = new Properties();
//
// properties.setProperty("org.apache.shiro.authz.UnauthorizedException", "/error/403");
//
// resolver.setExceptionMappings(properties);
//
// return resolver;
//
// }
//开启shiro注解支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
改写loginController下的login方法,对无权限用户实现拦截
@PostMapping("/login")
public String login(@RequestParam String username , @RequestParam String password,
HttpSession session, RedirectAttributes attributes) {
// User user = userService.checkUsers(username, password);
//
// if (user != null) {
// user.setPassword(null);
// session.setAttribute("user", user);
// return "admin/index";
// } else {
// attributes.addFlashAttribute("message", "用户名或密码错误");
// return "redirect:/admin";
// }
try {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
subject.login(token);
User user=(User)subject.getPrincipal();
session.setAttribute("user",user);
return "admin/index";
}catch (Exception e){
attributes.addFlashAttribute("message","用户名和密码错误1");
return "redirect:/admin";
}
}
效果展示
未登录用户,无法进入功能界面
新闻管理员用户只可以进入新闻管理界面, 不可进入类型管理和标签管理界面
springcloud eureka
provider
代码实现
修改serialization issues 设置
修改yml配置文件
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/provider?useSSL=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password:
mybatis:
type-aliases-package: com.xxxxbt.service.provider.po
创建user实体类
@Table(name = "tb_user")
public class User implements Serializable {
private static final long serialVersionUID = -6445192486418484948L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", birthday=" + birthday +
", created=" + created +
", updated=" + updated +
'}';
}
}
创建userService,用于从数据库中获取用户
@Service
public class UserService {
@Autowired(required = false)
private UserMapper userMapper;
public User queryById(Long id){
return this.userMapper.selectByPrimaryKey(id);
}
}
创建userMapper
@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends Mapper<User> {
}
添加控制器,根据url中的id,获取对应user对象
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("{id}")
public User queryById(@PathVariable("id") Long id){
return this.userService.queryById(id);
}
}
效果展示
consumer
代码实现
从provider复制user类,去掉注解
public class User implements Serializable {
private static final long serialVersionUID = -6445192486418484948L;
private Long id;
private String username;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", birthday=" + birthday +
", created=" + created +
", updated=" + updated +
'}';
}
}
创建控制器,从provider的url中获取所需user对象
@Controller
@RequestMapping("consumer/user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping
@ResponseBody
public User queryById(@RequestParam("id") Long id){
User user = this.restTemplate.getForObject("http://localhost:8081/user/"+id,User.class);
return user;
}
}
在主函数中注册RestTemplate
@SpringBootApplication
public class ConsumerApplication {
//注册RestTemplate
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
修改配置文件
server:
port: 8082
效果展示
erueka
代码实现
修改配置文件
server:
port: 8083
spring:
application:
name: eureka-server #应用名称
eureka:
client:
service-url:
defaultZone: http://localhost:${server.port}/eureka
在主函数上添加注解@EnableEurekaServer
@SpringBootApplication
@EnableEurekaServer //声明该应用为eureka服务中心
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
启动程序,进入8083端口即可进入界面
要把provider添加至erueka,还需进行以下操作
在pom.xml中添加依赖
<!-- Eureka客户端-->
</dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
修改配置文件
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/provider?useSSL=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password:
application:
name: service-provider #应用的名称,注册在eureka后的服务名称
mybatis:
type-aliases-package: com.xxxxbt.service.provider.po
eureka:
client:
service-url:
defaultZone: http://localhost:8083/eureka
在主函数中添加@EnableEurekaClient注解
@SpringBootApplication
@EnableEurekaClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
最终效果