栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Security 框架应用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Security 框架应用

Spring Security 框架应用

基于 t_account(用户表)和 t_role(角色)表实现自定义用户认证和授权,一个用户只能拥有一个角色

t_account 和 t_role 表结果如下所示,在 t_role 表中有三个角色,分别是管理员、店主和消费者:

 

1. 使用 Spring Initializr 新建一个 Spring Boot 框架项目,项目名自定义

框架中需要集成 Web 开发,并且修改 Spring boot 版本为 2.6.7。

2. 在项目中引入 Spring Security 依赖“spring-boot-starter-security”。
 
 
     org.springframework.boot
     spring-boot-starter-security
 
3.使用 UserDetailsService 身份认证方式实现用户登录和授权

基于 t_account(用户表)和 t_role(角色)两张表

实体类继承Security 框架中的User

 public class TAccountUser extends User {
     public TAccountUser(String username, String password, Collection authorities) {
         super(username, password, authorities);
     }
     private int accountId;
     private String roleName;
 ​
     public int getAccountId() {
         return accountId;
     }
 ​
     public void setAccountId(int accountId) {
         this.accountId = accountId;
     }
 ​
     public String getRoleName() {
         return roleName;
     }
 ​
     public void setRoleName(String roleName) {
         this.roleName = roleName;
     }
 }

service

 @Service
 public class IndexUserDetailsService implements UserDetailsService {
     @Autowired
     private IndexMapper indexMapper;
     @Override
     public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException{
         BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
         //查询用户信息
         TAccount account=indexMapper.selectUser(username);
         //将用户信息封装成account返回
         if (account==null){
             throw new UsernameNotFoundException("用户名不存在");
         }else {
             List list=new ArrayList<>();
             list.add(new SimpleGrantedAuthority(account.getTRole().getRoleCode()));
             TAccountUser user=new TAccountUser(account.getUsername(),account.getPassword(),list);
             user.setAccountId(account.getId());
             user.setRoleName(account.getTRole().getRoleName());
             System.out.println(user.getRoleName());
             return user;
         }
     }
 }

config

//定制用户认证管理器来实现用户认证
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
     //UserDetailsService
     auth.userDetailsService(indexUserDetailsService).passwordEncoder(encoder);
 ​
 }

4.自定义用户登录页面。

在用户登录页面中,用户可以输入用户名和密码,提交表单完成登录。如果登录失败,登录页面需要有提示“用户名或密码错误,请重

新登录”。在自定义登陆页面使用持久化 Token 的方式实现“一周内免登录”功能。

  • 引入Thymeleaf对前端页面进行管理,引入依赖

    
     
         org.thymeleaf.extras
         thymeleaf-extras-springsecurity5
     
     
     
         org.springframework.boot
         spring-boot-starter-thymeleaf
     
     
         org.thymeleaf.extras
         thymeleaf-extras-java8time
     

  • 引入security的名称空间;

 
  • 前端页面

  • config

 protected void configure(HttpSecurity http) throws Exception {
 ​
         //定制http请求的用户授权
         http.authorizeRequests()
                 .antMatchers("/toLogin").permitAll()
                 .antMatchers("/").permitAll()
                 .antMatchers("/css/**","/js/**","/image/**").permitAll()
                 .antMatchers("/main").permitAll()
                 .and().formLogin();
 ​
         //自定义登录界面
         http.formLogin()
                 //配置登录界面
                 .loginPage("/toLogin").permitAll()
                 //配置登录表单提交路径(post提交)
                 .loginProcessingUrl("/login").permitAll()
                 .defaultSuccessUrl("/main")
                 //配置登录失败后跳转地址
                 .failureUrl("/toLogin?error");
 ​
         //关闭csrf
         http.csrf().disable();
 ​
         //开启退出配置
         //logoutSuccessUrl是指的注销成功后跳转的url,而logoutUrl是指定的注销需要访问的url
         http.logout()
                 .logoutUrl("/logout")
                 .logoutSuccessUrl("/toLogin");
         //开启记住我配置
         //记住我功能默认是两周
         http.rememberMe()
                 .rememberMeParameter("remember")
                 .tokenRepository(tokenRepository())
                 .tokenValiditySeconds(604800);
 ​
         //异常处理
         http.exceptionHandling()
                 .accessDeniedPage("/warn");
 ​
     }
 ​
     @Bean
     public JdbcTokenRepositoryImpl tokenRepository(){
         JdbcTokenRepositoryImpl impl=new JdbcTokenRepositoryImpl();
         impl.setDataSource(dataSource);
         return impl;
     }

5. 用户登录成功后,跳转到用户管理后台。

管理员、店主和消费者的菜单可自拟,不同的用户显示不同的菜单。

  • controller

 //跳到main页面
 @RequestMapping("/main")
 public String mainPage(Authentication authentication, Model model){
     TAccountUser user=(TAccountUser) authentication.getPrincipal();
     model.addAttribute("tAccountUser",user);
     return "main";
 }
  • 前端页面

 

6.实现退出功能

在用户管理后台界面添加退出系统超链接,实现退出功能,用户退出后,跳转到登录页面。

  • 判断是否登录,登录后就显示退出

  •  

     

  • 在config类中配置

 //开启退出配置
 //logoutSuccessUrl是指的注销成功后跳转的url,而logoutUrl是指定的注销需要访问的url
 http.logout()
     .logoutUrl("/logout")
     .logoutSuccessUrl("/toLogin");

7.总结
  • th:action中自带token值;

  • 在Security中,通过重写WebSecurityConfigurerAdapter类的configure(HttpSecurity http)方法,可以实现用户访问控制;

  • 使用HttpSecurity类提供的formLogin()方法可以对基于表单的用户登录进行配置;

  • Spring Boot项目中引入Spring Security框架后会自动开启CSRF防护功能(跨站请求伪造防护),用户退出时必须使用POST请求;如果关闭了CSRF防护功能,那么可以使用任意方式的HTTP请求进行用户注销。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号