微服务迁移记(五):WEB层搭建(2)-SpringSecurity集成
一、redis搭建
二、WEB层主要依赖包
三、FeignClient通用接口
以上三项,参考《微服务迁移记(五):WEB层搭建(1)》
接下来,集成SpringSecruity,实现用户登录。
总体思路为:自定义UserDetails、UserDetailsService,重载WebSecurityConfigurerAdapter实现自定义表单登录,将菜单和按钮权限也扔到SpringSecruity的Session里。
四、SpringSecurity集成
1. 自定义MyUserDetails,实现UserDetails接口
1)我在里面多定义了一个UserEntity实体,通过get方法可以拿到这个实体,实现前台的一些业务逻辑。
RoleTreefuncEntity是功能权限树,也扔到session里。
2)isAccountNonExpired、isAccountNonLocked、isCredentialsNonExpired、isEnabled这几个方法,因为我直接从用户表取 del_flag=0的用户,不判断用户禁用或过期等状态,都直接返回true了。
package com.zyproject.web.secrity; import com.zyproject.entity.RoleTreefuncEntity;
import com.zyproject.entity.UserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection;
import java.util.List; /**
* @program: zyproject
* @description: 实现SpringSercrity UserDetails
* @author: zhouyu(zhouyu629 # qq.com)
* @create: 2020-02-12
**/
public class MyUserDetails implements UserDetails { private UserEntity userEntity; //用户实体
//将用户所有的角色菜单权限放到内存中,供校验使用
private List<RoleTreefuncEntity> roleTreefuncEntities; public MyUserDetails(UserEntity userEntity,List<RoleTreefuncEntity> roleTreefuncEntities){
this.userEntity = userEntity;
this.roleTreefuncEntities = roleTreefuncEntities;
} //获取用户真实姓名
public String getRealName(){
return userEntity.getUser_name();
} //获取用户实体
public UserEntity getUserEntity(){
return this.userEntity;
} //获取权限菜单
public List<RoleTreefuncEntity> getTreefuncEntities(){return this.roleTreefuncEntities;} @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
} @Override
public String getPassword() {
return userEntity.getLogin_password();
} @Override
public String getUsername() {
return userEntity.getLogin_code();
} @Override
public boolean isAccountNonExpired() {
return true;
} @Override
public boolean isAccountNonLocked() {
return true;
} @Override
public boolean isCredentialsNonExpired() {
return true;
} @Override
public boolean isEnabled() {
return true;
}
}
2. 自定义MyUserDetailsService接口,实现UserDetailsService接口
package com.zyproject.web.secrity; import com.google.gson.Gson;
import com.zyproject.common.CodeEnum;
import com.zyproject.common.ResponseData;
import com.zyproject.entity.RoleTreefuncEntity;
import com.zyproject.entity.UserEntity;
import com.zyproject.web.service.TreeService;
import com.zyproject.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.Service; import java.util.Arrays;
import java.util.List; /**
* @program: zyproject
* @description: 实现SpringSecrity UserDetailService接口
* @author: zhouyu(zhouyu629 # qq.com)
* @create: 2020-02-12
**/
@Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private TreeService treeService; @Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
ResponseData<UserEntity> userResult = userService.findByLoginname(s);
UserEntity user = new UserEntity();
if(userResult.getCode() == CodeEnum.SUCCESS.getCode()){
user = userResult.getData(UserEntity.class);
ResponseData rightResult = treeService.getRoleTreefuncByUserid(user.getUser_id());
Gson gson = new Gson();
List<RoleTreefuncEntity> roleTreefuncEntities = Arrays.asList(gson.fromJson(gson.toJson(rightResult.getData()),RoleTreefuncEntity[].class));
return new MyUserDetails(user,roleTreefuncEntities);
}else{
throw new UsernameNotFoundException(s);
}
}
}
3. SecurityConfiguration配置
1) 覆写protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder),实现MD5密码校验
2) protected void configure(HttpSecurity httpSecurity),实现自定义表单登录
package com.zyproject.web.secrity; import org.springframework.beans.factory.annotation.Autowired;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* @program: zyproject
* @description: SpringSercrity配置
* @author: zhouyu(zhouyu629 # qq.com)
* @create: 2020-02-12
**/
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired
private MyUserDetailService myUserDetailService; @Autowired
private MyAuthenctiationFailureHandler myAuthenctiationFailureHandler; @Autowired
private MyAuthenctiationSucessHandler myAuthenctiationSucessHandler; @Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder.userDetailsService(myUserDetailService).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return MD5Util.encode((String)charSequence);
} @Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(MD5Util.encode((String)charSequence));
}
});
} @Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.headers().frameOptions().disable();
httpSecurity
.authorizeRequests()
.antMatchers("/manage/error","/manage/login/**","/manage/login-submit","/manage/images/**","/manage/js/**","/manage/css/**","/manage/fonts/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
//指定登录路径
.loginPage("/manage/login")
.loginProcessingUrl("/manage/login-submit") //表单请求的路径,貌似无用,已经在config里做密码校验了
.failureHandler(myAuthenctiationFailureHandler)
.successHandler(myAuthenctiationSucessHandler)
.failureUrl("/manage/error?key=1002")
.defaultSuccessUrl("/manage/index")
.usernameParameter("username")
.passwordParameter("password")
//必须允许所有用户访问我们的登录页(例如未验证的用户,否则验证流程就会进入死循环)
.permitAll()
.and()
.sessionManagement()
.invalidSessionUrl("/manage/error?key=timeout");
//默认都会产生一个hiden标签 里面有安全相关的验证 防止请求伪造 这边我们暂时不需要 可禁用掉
httpSecurity.csrf().disable();
} @Override
public void configure(WebSecurity webSecurity) throws Exception{
super.configure(webSecurity);
}
}
五、FreeMarker集成
待续
六、权限管理
待续
微服务迁移记(五):WEB层搭建(2)-SpringSecurity集成的更多相关文章
- 微服务迁移记(五):WEB层搭建(5)-集成ueditor编辑器,伪分布式图片上传
一.redis搭建 二.WEB层主要依赖包 三.FeignClient通用接口 以上三项,参考<微服务迁移记(五):WEB层搭建(1)> 四.SpringSecurity集成 参考:< ...
- 微服务迁移记(五):WEB层搭建(3)-FreeMarker集成
一.redis搭建 二.WEB层主要依赖包 三.FeignClient通用接口 以上三项,参考<微服务迁移记(五):WEB层搭建(1)> 四.SpringSecurity集成 参考:< ...
- 微服务迁移记(五):WEB层搭建(4)-简单的权限管理
一.redis搭建 二.WEB层主要依赖包 三.FeignClient通用接口 以上三项,参考<微服务迁移记(五):WEB层搭建(1)> 四.SpringSecurity集成 参考:< ...
- 微服务迁移记(五):WEB层搭建(1)
WEB层是最终表现层,注册至注册中心,引用接口层(不需要引用实现层).公共服务层.用户登录使用SpringSecurity,Session保存在redis中,权限管理没有用SpringSecurity ...
- docker微服务部署之:二、搭建文章微服务项目
docker微服务部署之:一,搭建Eureka微服务项目 一.新增demo_article模块,并编写代码 右键demo_parent->new->Module->Maven,选择M ...
- docker微服务部署之:三,搭建Zuul微服务项目
docker微服务部署之:二.搭建文章微服务项目 一.新增demo_eureka模块,并编写代码 右键demo_parent->new->Module->Maven,选择Module ...
- docker微服务部署之:一,搭建Eureka微服务项目
先说明一下docker需要搭建的微服务的基本情况: 项目情况:一个demo_parent项目,下面三个子模块:demo_eureka(eureka服务).demo_article(文章服务).demo ...
- 微服务实践(五):微服务的事件驱动数据管理 - DockOne.io
原文:微服务实践(五):微服务的事件驱动数据管理 - DockOne.io [编者的话]本文是使用微服务创建应用系列的第五篇文章.第一篇文章介绍了微服务架构模式,并且讨论了使用微服务的优缺点:第二和第 ...
- .Net微服务实践(五)[服务发现]:Consul介绍和环境搭建
目录 介绍 服务发现 健康检查.键值存储和数据中心 架构 Consul模式 环境安装 HTTP API 和Command CLI 示例API介绍 最后 在上篇.Net微服务实践(四)[网关]:Ocel ...
随机推荐
- 半导体质量管理(LineWorks)_SPACE(统计过程分析和控制环境)
LineWorks作为SEMI的质量管理,可为半导体制造商提供对实施标准,产品质量,质量和指标验证的全面控制.有许多附加模块和SPACE-Chart插件,可根据个人需求进行灵活调整. 三个主要特征是: ...
- 理解css中Grid布局,在项目中如何实现grid页面布局
简介 CSS中Grid是一种二维网格式布局方式.我们常规使用table.float.position.inline-block等布局,但它们遗漏了很多功能,例如垂直居中.后来css3中flexbox的 ...
- 免费馅饼——移动dp
免费馅饼 题目描述 SERKOI最新推出了一种叫做"免费馅饼"的游戏: 游戏在一个舞台上进行.舞台的宽度为 \(W\) 格,天幕的高度为 \(H\) 格,游戏者占一格. 开始时游戏 ...
- 洛谷 P2607 [ZJOI2008]骑士 树形DP
题目描述 Z国的骑士团是一个很有势力的组织,帮会中汇聚了来自各地的精英.他们劫富济贫,惩恶扬善,受到社会各 界的赞扬.最近发生了一件可怕的事情,邪恶的Y国发动了一场针对Z国的侵略战争.战火绵延五百里, ...
- java语法学习
// 单行注释 /* 多行注释 */ /** JavaDoc(Java文档)注释是这样的.可以用来描述类和类的属性. */ // 导入 java.util中的 ArrayList 类 import j ...
- day13 作业
目录 1.编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改 2.编写tail工具 3.编写登录功能 4.编写注册功能 选做题:编写ATM程序实 ...
- python numpy 保留满足指定条件的行
#arr_old 原来数组 #arr_new 保留后的数组 #>=mean+std 指定条件 arr_new = arr_old[arr_old[:,4]>=(mean+std),:]#筛 ...
- shell专题(四):Shell中的变量
4.1 系统变量 1. 常用系统变量 $HOME.$PWD.$SHELL.$USER等 2.案例实操 (1)查看系统变量的值 [atguigu@hadoop101 datas]$ echo $HOME ...
- 【翻译】.NET 5中的性能改进
[翻译].NET 5中的性能改进 在.NET Core之前的版本中,其实已经在博客中介绍了在该版本中发现的重大性能改进. 从.NET Core 2.0到.NET Core 2.1到.NET Core ...
- .NET 开源项目 StreamJsonRpc 介绍[下篇]
阅读本文大概需要 9 分钟. 大家好,这是 .NET 开源项目 StreamJsonRpc 介绍的最后一篇.上篇介绍了一些预备知识,包括 JSON-RPC 协议介绍,StreamJsonRpc 是一个 ...