Springboot整合SpringSecurity实现登录认证和鉴权

时间: 2024-02-28 10:43:47 浏览: 25
好的,Spring Boot整合Spring Security实现登录认证和鉴权可以分为以下几个步骤: 1. 添加Spring Security依赖:在pom.xml文件中添加Spring Security依赖。 2. 配置Spring Security:创建一个配置类,继承WebSecurityConfigurerAdapter,重写configure(HttpSecurity http)和configure(AuthenticationManagerBuilder auth)方法,配置登录认证和鉴权的相关信息。 3. 创建登录页面:在templates目录下创建login.html页面,用于用户登录。 4. 创建登录处理接口:创建一个controller接口,用于处理用户登录请求。 5. 创建用户实体类和用户服务类:创建一个用户实体类,用于存储用户信息;创建一个用户服务类,用于查询用户信息。 6. 配置密码加密:在用户服务类中,使用BCryptPasswordEncoder对密码进行加密。 7. 测试登录认证和鉴权功能:启动应用程序,访问login.html页面,输入正确的用户名和密码,验证登录认证功能;访问受保护的资源,验证鉴权功能。 以上就是Spring Boot整合Spring Security实现登录认证和鉴权的基本步骤。
相关问题

springboot整合spring security 实现用户登录注册与鉴权全记录

1. 引入依赖 在pom.xml文件中引入Spring Security依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 添加配置类 在项目中添加一个配置类SecurityConfig,继承自WebSecurityConfigurerAdapter。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/register").permitAll() // 登录注册页面不需要验证 .anyRequest().authenticated() // 其他页面需要验证 .and() .formLogin() .loginPage("/login") // 登录页面 .defaultSuccessUrl("/index") // 登录成功后的默认跳转页面 .and() .logout() .logoutUrl("/logout") // 退出登录的URL .logoutSuccessUrl("/login") // 退出登录后跳转到的页面 .invalidateHttpSession(true) .deleteCookies("JSESSIONID"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // 在内存中存储用户信息 .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}user").roles("USER"); } } ``` 3. 实现登录与注册功能 创建登录页面login.html和注册页面register.html,使用Thymeleaf模板引擎渲染页面。 在Controller中添加登录和注册的请求处理方法。 ``` @Controller public class UserController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") public String loginSuccess() { return "redirect:/index"; } @GetMapping("/register") public String register() { return "register"; } @PostMapping("/register") public String registerSuccess() { return "redirect:/login"; } } ``` 4. 实现用户鉴权功能 在SecurityConfig中重写configure(AuthenticationManagerBuilder auth)方法,实现用户信息的认证。 这里使用inMemoryAuthentication()方法在内存中存储用户信息,实际应用中可以使用数据库存储。 ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // 在内存中存储用户信息 .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}user").roles("USER"); } ``` 在Controller中添加需要鉴权的请求处理方法,并在方法上添加@PreAuthorize注解指定需要的权限。 ``` @Controller public class UserController { @GetMapping("/admin") @PreAuthorize("hasRole('ADMIN')") public String admin() { return "admin"; } @GetMapping("/user") @PreAuthorize("hasRole('USER')") public String user() { return "user"; } } ``` 5. 配置登录认证 在SecurityConfig中重写configure(HttpSecurity http)方法,配置登录认证信息。 ``` @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/register").permitAll() // 登录注册页面不需要验证 .anyRequest().authenticated() // 其他页面需要验证 .and() .formLogin() .loginPage("/login") // 登录页面 .defaultSuccessUrl("/index") // 登录成功后的默认跳转页面 .and() .logout() .logoutUrl("/logout") // 退出登录的URL .logoutSuccessUrl("/login") // 退出登录后跳转到的页面 .invalidateHttpSession(true) .deleteCookies("JSESSIONID"); } ``` 6. 测试 启动应用,在浏览器中访问http://localhost:8080/login,输入用户名和密码进行登录,登录成功后跳转到首页。 访问http://localhost:8080/admin和http://localhost:8080/user,根据用户角色的不同,页面会有不同的显示。如果访问没有权限的页面,会自动跳转到登录页面。在登录状态下访问/logout可以退出登录。

springboot中整合springsecurity实现登录认证和数据权限管理

在Spring Boot中整合Spring Security可以实现登录认证和数据权限管理。下面是简单的步骤: 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置Spring Security 在主配置类中添加@EnableWebSecurity注解,开启Spring Security,并且创建一个继承自WebSecurityConfigurerAdapter的配置类,用于配置Spring Security。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 配置登录页面和登录请求的路径 http.formLogin() .loginPage("/login") .loginProcessingUrl("/login") .defaultSuccessURL("/home") .and() // 配置退出登录的路径和跳转页面 .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .and() // 配置拦截规则 .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() // 关闭CSRF保护 .csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置用户信息和密码加密方式 auth.inMemoryAuthentication() .passwordEncoder(new BCryptPasswordEncoder()) .withUser("admin") .password(new BCryptPasswordEncoder().encode("admin")) .roles("ADMIN"); } } ``` 3. 配置数据权限管理 如果需要实现数据权限管理,可以在配置类中添加一个实现了FilterInvocationSecurityMetadataSource接口的类,用于获取当前请求所需的权限信息,并且在配置类中添加一个实现了AccessDecisionManager接口的类,用于判断当前用户是否有访问该资源的权限。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource; @Autowired private CustomAccessDecisionManager customAccessDecisionManager; @Override protected void configure(HttpSecurity http) throws Exception { // 配置拦截规则 http.authorizeRequests() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O object) { object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource); object.setAccessDecisionManager(customAccessDecisionManager); return object; } }) .and() // 关闭CSRF保护 .csrf().disable(); } } ``` 参考资料: 1. Spring Security官方文档:https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/ 2. Spring Boot整合Spring Security实现登录认证和数据权限管理:https://www.jianshu.com/p/04d848c9cb8d

相关推荐

最新推荐

recommend-type

SpringBoot + SpringSecurity 短信验证码登录功能实现

主要介绍了SpringBoot + SpringSecurity 短信验证码登录功能实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

SpringBoot集成SpringSecurity和JWT做登陆鉴权的实现

主要介绍了SpringBoot集成SpringSecurity和JWT做登陆鉴权的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

主要介绍了Springboot+SpringSecurity+JWT实现用户登录和权限认证示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

SpringBoot+SpringSecurity处理Ajax登录请求问题(推荐)

主要介绍了SpringBoot+SpringSecurity处理Ajax登录请求问题,本文给大家介绍的非常不错,具有参考借鉴价值,需要的朋友可以参考下
recommend-type

详解用JWT对SpringCloud进行认证和鉴权

主要介绍了详解用JWT对SpringCloud进行认证和鉴权,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

RTL8188FU-Linux-v5.7.4.2-36687.20200602.tar(20765).gz

REALTEK 8188FTV 8188eus 8188etv linux驱动程序稳定版本, 支持AP,STA 以及AP+STA 共存模式。 稳定支持linux4.0以上内核。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

Redis验证与连接:快速连接Redis服务器指南

![Redis验证与连接:快速连接Redis服务器指南](https://img-blog.csdnimg.cn/20200905155530592.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNTg5NTEw,size_16,color_FFFFFF,t_70) # 1. Redis验证与连接概述 Redis是一个开源的、内存中的数据结构存储系统,它使用键值对来存储数据。为了确保数据的安全和完整性,Redis提供了多
recommend-type

gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker app:app 报错 ModuleNotFoundError: No module named 'geventwebsocket' ]

这个报错是因为在你的环境中没有安装 `geventwebsocket` 模块,可以使用下面的命令来安装: ``` pip install gevent-websocket ``` 安装完成后再次运行 `gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker app:app` 就不会出现这个报错了。
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。