77百科网
当前位置: 首页 生活百科

spring security 配置详解(SpringSecurity快速入门)

时间:2023-06-15 作者: 小编 阅读量: 1 栏目名: 生活百科

在配置文件中使用#如果在代码里配置了用户信息这个就不能使用了呢?spring.security.user.name=adminspring.security.user.password=123456spring.security.user.roles=ADMIN启动项目,localhost:8080/login进入页面,需要输入用户名和密码。

介绍如何使用springboot中Spring-security引入依赖包

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>

启动项目,localhost:8080/login 进入页面,需要输入用户名和密码。用户名为:user,密码在控制台输出,去控制台查找。

在配置文件中使用

#如果在代码里配置了用户信息 这个就不能使用了呢?spring.security.user.name=adminspring.security.user.password=123456spring.security.user.roles=ADMIN

启动项目,localhost:8080/login 进入页面,需要输入用户名和密码。用户名为:admin,密码:123456

在内存中使用
  • (需要将配置文件里配置的注释掉)

@Configuration@EnableWebSecurity//启用Spring security@EnableGlobalMethodSecurity(prePostEnabled = true)//拦截@preAuthrize注解的配置public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate PasswordEncoder encoder;//这个东西很重要@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {/** 基于内存的方式构建两个账户* */auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("admin");//两个构建账户的方式 看着不同 其实是一样的啊auth.inMemoryAuthentication().passwordEncoder(encoder).withUser("user").password(encoder.encode("123")).roles("normal");}}

在内存中定义认证用户,需要自己写一个类WebSecurityConfig实现WebSecurityConfigurerAdapter类,重写其中的方法;

需要注意的是:在设置密码的时候,需要是加密后的密码,且要符合加密类型;

类上面的注解 @EnableGlobalMethodSecurity开启后针对不同的方法,会验证其身份角色;

@RestControllerpublicclassHelloController{@GetMapping(value ="/hello")publicStringhello(){return"HelloWorld";}@GetMapping(value ="/helloAdmin")@PreAuthorize("hasAnyRole('admin')")publicStringhelloAdmin(){return"HelloWorld,helloAdmin";}@PreAuthorize("hasAnyRole('normal','admin')")@GetMapping(value ="/helloUser")publicStringhelloUser(){return"HelloWorld,helloUser";}}

验证:

进入localhost:8080/login,登录 admin用户,再访问:localhost:8080/helloAdmin ,localhost:8080/helloUser

均可访问成功;

重新登入 user用户,再访问localhost:8080/helloAdmin ,localhost:8080/helloUser,发现访问localhost:8080/helloAdmin时报错,访问被禁止

使用数据库1 添加依赖,使具备查询数据库的能

<!-- 数据库连接--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!--数据库--><dependency><groupId>org.hsqldb</groupId><artifactId>hsqldb</artifactId><scope>runtime</scope></dependency>

hsqldb内存数据库,jpa 连接数据库

2 开发一个根据用户名查询用户信息的接口

publicinterfaceUserInfoService{publicUserInfofindByUsername(String username);}

3 编写一个类CustomUserDetailsService实现接口UserDetailsService 重写loadUserByUsername方法

@ComponentpublicclassCustomUserDetailsServiceimplementsUserDetailsService{@AutowiredprivateUserInfoService service;@AutowiredprivatePasswordEncoder encoder;@OverridepublicUserDetailsloadUserByUsername(String s)throwsUsernameNotFoundException{UserInfo userInfo = service.findByUsername(s);if(userInfo ==null) {thrownewUsernameNotFoundException("not found : "s);}List<GrantedAuthority> authorities =newArrayList<>();authorities.add(newSimpleGrantedAuthority("ROLE_"userInfo.getRole().name()));User userDetails =newUser(userInfo.getUsername(), encoder.encode(userInfo.getPassword()), authorities);returnuserDetails;}}

1 此方法返回的是一个UserDetails 实例,构造方法中有3个参数,分别为 用户名,密码,和权限列表;

2 次用用到了查询用户信息的接口

注意:此处的密码需要加密;权限需要前面拼接ROLE(权限如果提前预存在数据库已经拼接过,此处写法会不同)

4 在数据库添加用户

@ServicepublicclassDataInit{@AutowiredprivateUserInfoRepository userInfoRepository;@PostConstructpublicvoiddataInit(){UserInfo user =newUserInfo();user.setUsername("user");user.setPassword("123");user.setRole(UserInfo.Role.normal);userInfoRepository.save(user);UserInfo admin =newUserInfo();admin.setUsername("admin");admin.setPassword("123");admin.setRole(UserInfo.Role.admin);userInfoRepository.save(admin);}}

@ServicepublicclassDataInit{@AutowiredprivateUserInfoRepository userInfoRepository;@PostConstructpublicvoiddataInit(){UserInfo user =newUserInfo();user.setUsername("user");user.setPassword("123");user.setRole(UserInfo.Role.normal);userInfoRepository.save(user);UserInfo admin =newUserInfo();admin.setUsername("admin");admin.setPassword("123");admin.setRole(UserInfo.Role.admin);userInfoRepository.save(admin);}}

验证:

进入localhost:8080/login,登录 admin用户,再访问:localhost:8080/helloAdmin ,localhost:8080/helloUser

均可访问成功;

重新登入 user用户,再访问localhost:8080/helloAdmin ,localhost:8080/helloUser,发现访问localhost:8080/helloAdmin时报错,访问被禁止

源代码:https://github.com/liyiruo/bili-spring-security


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:

https://blog.csdn.net/l23456789o/article/details/107853160

,
    推荐阅读
  • 苏州居家隔离收费吗 苏州隔离自费吗

    居家隔离期间,门上将被贴上封条。如果有外出购买需要,请联系社区工作人员代为采购,采购费个人承担。共同居住人员要加强自我防护,做好自身健康监测,按要求做好家庭卫生防护。如身体出现发热、乏力、干咳等症状,应第一时间主动向属地医疗机构报告。

  • 番茄炒瘦肉如何做(瘦肉炒番茄怎么做)

    4、盖上锅盖闷2分钟,揭开锅继续翻炒一分钟,装盘。

  • 迷你世界蜂蜜有什么用(迷你世界蜂蜜的作用)

    迷你世界蜂蜜有什么用?只需要将蜂蜜和水结合在一起,它们就能够产生一种新的方块,这种方块叫作蜂蜜块,虽然说蜂蜜块不是食物,不能提供给玩家食用,但是它却是一种装饰材料,玩家可以用它来建造各种建筑。当遭遇到怪物时,用蜂蜜就能躲避怪物的攻击,只要在地上挖一个深坑,然后在坑中倒满蜂蜜,这时候我们就可以躲入蜂蜜之中了,因为我们在蜂蜜中是不会缺氧的,所以想呆多久就呆多久,这样就不会被攻击到了。

  • 成植物人算脱离生命危险吗(最小植物人存活9年后离世)

    那一天的急诊病例显示,接诊医生将尧尧的症状记录为“支气管炎”。此外,性别被错写成了“女”。而当天急救过程中拍摄的X光胸片则显示,尧尧“双侧肺野内可见较多斑片状模糊影,示重症肺炎”。ICU花费高昂,唐运章交付近8万元医药费后,几乎身无分文,又借了一万,4天花完。2015年,尧尧进入ICU5年后,湖南省儿童医院起诉唐运章不交医药费,“医院的做法都是合理合规的,家属应该负担患儿的医疗费。”唐运章的案子还未宣判。

  • 小腿抽筋疼痛是怎么回事不缺钙(小腿经常抽筋不一定是缺钙)

    所以当中老年人经常腿抽筋时,就要到医院及时检查血管是否健康,避免耽误病情。

  • 泡茶正确的方法(如何正确泡茶)

    泡茶正确的方法?接下来我们就一起去研究一下吧!泡茶的时候,水温也有讲究,绿茶比较嫩,所以不可以使用沸水,八十五度的开水便可以,红茶最好是用九十多度的水温最佳。冲泡茶的时候,要心平气和,一个人心浮气躁,绝对喝不出茶的真滋味。让自己静静坐下,慢慢洗茶、倒水、泡茶、倒茶,然后品茶,这个过程最滋养身心。

  • 数字人民币相城生活服务平台入口(相城数字经济)

    数字人民币相城生活服务平台:点击进入今年以来,各种应用场景频频在相城落地,参与数字人民币试点的新步伐不断加快。2021年,逐步推进50个数字人民币应用试点场景,涵盖了扩面场景、政务服务、生活服务、交通出行、乡村振兴、综合试点场景、特色应用场景等多个方面,截至目前,已完成或阶段性完成场景近30个。■相城全域10个水费充值网点、11个燃气缴费网点均支持数字人民币支付。■局部可使用数字人民币支付充电桩充电费用。

  • 卡通无线耳机教程(手机与蓝牙耳机配对)

    接下来我们就一起去了解一下吧!卡通无线耳机教程

  • 欧式双眼皮适合的眼型(单眼皮VS欧式大双眼皮)

    娱乐圈近两年冒出了许多单眼皮男神,刚开始还是以黄轩为代表吧。画风突变JonyJ,从老帅的谢君豪到潮帅的JonyJ跨度有点大妹妹承认。标准欧式大双眼皮父子,刘诺一和他十八岁的爹地刘烨。两人都是超标准准的大双眼皮。虽然妹妹个人觉得诺一更加纯正,刘烨也就是跟着诺一上上榜。最后送一张单眼皮战队和欧式大双眼皮战队的队员合照。友谊第一,比赛第二。图源来自网络,如有异议请联系删除。

  • 杨丞琳个人简历(高中辍学为父还债)

    高中辍学为父还债戳右边关注我们,每天都有最新娱乐八卦等你批阅!9月19号,李荣浩与杨丞琳大方官宣领证,至此,这段蚌埠青年与台湾女子的故事,终于走进新篇章也象征着,经历数次失败感情的杨丞琳,赫然翻盘​当下,作为内地媳妇。