超全的springboot+springsecurity实现前后端分离简单实现!
java1234
共 9047字,需浏览 19分钟
· 2020-12-13
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
1、前言部分
1.1、唠嗑部分(如何学习?)
1.2、技术支持
1.3、预期实现效果图
2、核心部分
2.1、springsecurity原理解释:
2.2、踩坑集锦
访问/login时必须要用post方法!, 访问的参数名必须为username和password
访问/logout时即可用post也可用get方法!
//springsecurity配置文件中的hasRole("")不能以ROLE开头,比如ROLE_USER就是错的,springsecurity会默认帮我们加上,但数据库的权限字段必须是ROLE_开头,否则读取不到
2.3、代码部分
com.google.code.gson
gson
2.8.2
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-security
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.4.1
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.security
spring-security-config
5.3.4.RELEASE
org.springframework.security
spring-security-web
5.3.4.RELEASE
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Msg {
int code; //错误码
String Message; //消息提示
Mapdata=new HashMap (); //数据
//无权访问
public static Msg denyAccess(String message){
Msg result=new Msg();
result.setCode(300);
result.setMessage(message);
return result;
}
//操作成功
public static Msg success(String message){
Msg result=new Msg();
result.setCode(200);
result.setMessage(message);
return result;
}
//客户端操作失败
public static Msg fail(String message){
Msg result=new Msg();
result.setCode(400);
result.setMessage(message);
return result;
}
public Msg add(String key,Object value){
this.data.put(key,value);
return this;
}
}
@Data
public class User implements Serializable {
private Integer id;
private String account;
private String password;
private String role;
}
@Repository
public interface UserMapper extends BaseMapper{
}
public interface UserService{
}
@Service
public class UserServiceImpl extends ServiceImplimplements UserService,UserDetailsService {
@Autowired
UserMapper userMapper;
//加载用户
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//mybatis-plus帮我们写好了sql语句,相当于 select * from user where account ='${account}'
QueryWrapperwrapper=new QueryWrapper<>();
wrapper.eq("account",s);
User user=userMapper.selectOne(wrapper); //user即为查询结果
if(user==null){
throw new UsernameNotFoundException("用户名错误!!");
}
//获取用户权限,并把其添加到GrantedAuthority中
ListgrantedAuthorities=new ArrayList<>();
GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(user.getRole());
grantedAuthorities.add(grantedAuthority);
//方法的返回值要求返回UserDetails这个数据类型, UserDetails是接口,找它的实现类就好了
//new org.springframework.security.core.userdetails.User(String username,String password,Collection extends GrantedAuthority> authorities) 就是它的实现类
return new org.springframework.security.core.userdetails.User(s,user.getPassword(),grantedAuthorities);
}
}
@RestController
public class UserController {
@GetMapping("index")
public String index(){
return "index";
}
@GetMapping("hello")
public String hello(){
return "hello";
}
}
@Component
public class AuthenticationEnryPoint implements AuthenticationEntryPoint {
@Autowired
Gson gson;
//未登录时返回给前端数据
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
Msg result=Msg.fail("需要登录!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
//登录失败返回给前端消息
@Component
public class AuthenticationFailure implements AuthenticationFailureHandler{
@Autowired
Gson gson;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
Msg msg=null;
if(e instanceof UsernameNotFoundException){
msg=Msg.fail(e.getMessage());
}else if(e instanceof BadCredentialsException){
msg=Msg.fail("密码错误!!");
}else {
msg=Msg.fail(e.getMessage());
}
//处理编码方式,防止中文乱码的情况
response.setContentType("text/json;charset=utf-8");
//返回给前台
response.getWriter().write(gson.toJson(msg));
}
}
@Component
public class AuthenticationSuccess implements AuthenticationSuccessHandler{
@Autowired
Gson gson;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//登录成功时返回给前端的数据
Msg result=Msg.success("登录成功!!!!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class AuthenticationLogout implements LogoutSuccessHandler{
@Autowired
Gson gson;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Msg result=Msg.success("注销成功");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
//无权访问
@Component
public class AccessDeny implements AccessDeniedHandler{
@Autowired
Gson gson;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
Msg result= Msg.denyAccess("无权访问,need Authorities!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class SessionInformationExpiredStrategy implements org.springframework.security.web.session.SessionInformationExpiredStrategy{
@Autowired
Gson gson;
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
Msg result= Msg.fail("您的账号在异地登录,建议修改密码");
HttpServletResponse response=event.getResponse();
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider{
@Autowired
UserServiceImpl userServiceImpl;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String account= authentication.getName(); //获取用户名
String password= (String) authentication.getCredentials(); //获取密码
UserDetails userDetails= userServiceImpl.loadUserByUsername(account);
boolean checkPassword= bCryptPasswordEncoder.matches(password,userDetails.getPassword());
if(!checkPassword){
throw new BadCredentialsException("密码不正确,请重新登录!");
}
return new UsernamePasswordAuthenticationToken(account,password,userDetails.getAuthorities());
}
@Override
public boolean supports(Class> aClass) {
return true;
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启权限注解,默认是关闭的
public class SpringsecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthenticationEnryPoint authenticationEnryPoint; //未登录
@Autowired
AuthenticationSuccess authenticationSuccess; //登录成功
@Autowired
AuthenticationFailure authenticationFailure; //登录失败
@Autowired
AuthenticationLogout authenticationLogout; //注销
@Autowired
AccessDeny accessDeny; //无权访问
@Autowired
SessionInformationExpiredStrategy sessionInformationExpiredStrategy; //检测异地登录
@Autowired
SelfAuthenticationProvider selfAuthenticationProvider; //自定义认证逻辑处理
@Bean
public UserDetailsService userDetailsService() {
return new UserServiceImpl();
}
//加密方式
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(selfAuthenticationProvider);
}
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//cors()解决跨域问题,csrf()会与restful风格冲突,默认springsecurity是开启的,所以要disable()关闭一下
http.cors().and().csrf().disable();
// /index需要权限为ROLE_USER才能访问 /hello需要权限为ROLE_ADMIN才能访问
http.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers("/hello").hasRole("ADMIN")
.and()
.formLogin() //开启登录
.permitAll() //允许所有人访问
.successHandler(authenticationSuccess) // 登录成功逻辑处理
.failureHandler(authenticationFailure) // 登录失败逻辑处理
.and()
.logout() //开启注销
.permitAll() //允许所有人访问
.logoutSuccessHandler(authenticationLogout) //注销逻辑处理
.deleteCookies("JSESSIONID") //删除cookie
.and().exceptionHandling()
.accessDeniedHandler(accessDeny) //权限不足的时候的逻辑处理
.authenticationEntryPoint(authenticationEnryPoint) //未登录是的逻辑处理
.and()
.sessionManagement()
.maximumSessions(1) //最多只能一个用户登录一个账号
.expiredSessionStrategy(sessionInformationExpiredStrategy) //异地登录的逻辑处理
;
}
}
server:
port: 80
spring:
datasource:
url: jdbc:mysql://localhost:3306/springsecurity_test?characterEncoding=utf8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_42375707/article/details/110678638
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈
评论
真高!比亚迪员工爆料比亚迪在越南的薪资水平:基本工资480万,全勤奖35万,交通补助20万,餐补110万,每周6天,每天10小时
上一篇:某大公司为逼迫员工离职,竟然把他的工位安排到厕所旁,没想到他直接开始记录领导的如厕时间,还发到公司大群...对此,你怎么看?--完--PS:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。全文完,感谢你的耐心阅读。如果你还想看到我的文章,请一定给本
开发者全社区
0
太敢穿了!透视纱裙!性感火辣的身材
绝了呀今天的厂花:吴宣仪1995年1月26日,吴宣仪出生于海南省海口市,中国内地流行乐女歌手、影视演员。2016年2月,吴宣仪随宇宙少女发行首张迷你专辑正式出道。2018年4月,她参加《创造101》综艺选秀,获得第二名,成功加入火箭少女101组合。吴宣仪的颜值一直备受称赞,她的五官立体精致,皮肤白皙
逆锋起笔
0
某大公司为逼迫员工离职,竟然把他的工位安排到厕所旁,没想到他直接开始记录领导的如厕时间,还发到公司大群...
上一篇:字节的跳动职级与薪资(2024年)我们与公司间的合作,宛如两艘船只在茫茫大海上相互依靠,共同抵御风浪,携手驶向成功的彼岸。然而,当航向开始产生分歧,或是波涛汹涌的风浪改变了我们的初衷,我们或许应当冷静地选择和平分手,而非在风雨中硬撑。最近,一位网友的遭遇引起了广大职场人的关注和热议。这位网友
开发者全社区
0
金融研究 | 使用Python测量关键审计事项的「信息含量」
Tips: 公众号推送后内容只能更改一次,且只能改20字符。如果内容出问题,或者想更新内容, 只能重复推送。为了更好的阅读体验,建议阅读本文博客版, 链接地址https://textdata.cn/blog/2023-01-13-information-content-of-critical-aud
大邓和他的Python
0
我看阿里的年终奖总算发了!
到4月底了,这两天看朋友圈,发现阿里的年终奖终于发了,问了问老同学,也从网上检索了不少信息,基本搞清楚了阿里今年的年终奖情况。近来来阿里一些集团对绩效等级做了较大的调整,以前的旧绩效系统中,绩效分为3.25、3.5、3.75、4和5五个等级,其中4和5是较高绩效等级,较少见。而且之前3.5绩效内部划
公子龙
0
CVPR 2024|大视觉模型的开山之作!无需任何语言数据即可打造大视觉模型
↑ 点击蓝字 关注极市平台作者丨科技猛兽编辑丨极市平台极市导读 本文提出一种序列建模 (sequential modeling) 的方法,不使用任何语言数据,训练大视觉模型。>>加入极市CV技术交流群,走在计算机视觉的最前沿本文目录1 序列建模打造大视觉模型(来自 U
极市平台
1
金融研究(更新) | 使用Python构建关键审计事项的「信息含量」
Tips: 公众号推送后内容只能更改一次,且只能改20字符。如果内容出问题,或者想更新内容, 只能重复推送。为了更好的阅读体验,建议阅读本文博客版, 链接地址https://textdata.cn/blog/2023-01-13-information-content-of-critical-aud
大邓和他的Python
0
字节的跳动职级与薪资(2024年)
上一篇:阿里公布年终奖,P7, 3.5+,22W年终奖,还有35W长期现金激励,真香字节跳动自2012年3月成立以来,已经迅速成长为一个全球性的科技公司。其产品和服务已经遍布全球150多个国家与地区,并且支持超过75种不同的语言。在字节跳动的官方网站上,列出了一系列引人注目的产品和服务,包括但不限于
开发者全社区
0