SpringSecurity实现”记住我“功能

SpringSecurity实现”记住我“功能,第1张

SpringSecurity实现”记住我“功能

文章目录

1、配置类2、自定义逻辑3、登陆页4、持久层和控制层5、功能
功能: 简化用户每次登录都要输入用户名和密码的麻烦,提高用户体验

1、配置类

注意:
一定要添加lazy注解防止依赖循环

  @Resource
    @Lazy
    private UserServiceImpl userService;
    @Resource
    @Lazy
    private PersistentTokenRepository persistentTokenRepository;
package com.atmae.securitydemo.config;

import com.atmae.securitydemo.handle.MyAccessDeniedHandler;
import com.atmae.securitydemo.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Resource
    @Lazy
    private UserServiceImpl userService;
    @Resource
    private DataSource dataSource;
    @Resource
    @Lazy
    private PersistentTokenRepository persistentTokenRepository;

    @Bean
    public PersistentTokenRepository getPersistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        
     
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Bean
    public PasswordEncoder getPw() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                
                .loginProcessingUrl("/login")
                
                .loginPage("/login.html")
                
                .successForwardUrl("/index")
                
                .failureForwardUrl("/error");
        http.authorizeHttpRequests()
                
                .antMatchers("/error.html").permitAll()
                .antMatchers("/login.html").permitAll()
                .antMatchers("*.png").permitAll()
                
                .regexMatchers(".+[.]png").permitAll()
                
                
                
                
                
                .anyRequest().authenticated();
        
        http.csrf().disable();
        
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);
        
        http.rememberMe()
                
                .userDetailsService(userService)
                
                .tokenValiditySeconds(60)
                
                .tokenRepository(persistentTokenRepository);
    }
}
2、自定义逻辑
package com.atmae.securitydemo.service.impl;

import com.atmae.securitydemo.mapper.UserMapper;
import com.atmae.securitydemo.pojo.User;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        User user = userMapper.findUserByUsername(username);
        System.out.println(user);
        if (user == null) {
            throw new UsernameNotFoundException("用户名没有找到");
        }
        
        String password = passwordEncoder.encode(user.getPassword());
        return new org.springframework.security.core.userdetails.User(username, password, AuthorityUtils
                .commaSeparatedStringToAuthorityList("admin,normal0,ROLE_student0"));
    }
}
3、登陆页

记住我的name一定要是 remember-me 否则需要自己配置




    
    登录页





4、持久层和控制层
package com.atmae.securitydemo.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class UserController {

    @Secured("ROLE_student0")
    @PreAuthorize("hasRole('ROLE_student0')") 
    @RequestMapping("/index")
    public String indexPage() {
        return "redirect:index.html";
    }

}
package com.atmae.securitydemo.mapper;

import com.atmae.securitydemo.pojo.User;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface UserMapper {

    
    User findUserByUsername(String username);
}
5、功能

第一次登录


自动生成的数据表

第二次登录直接进入登录页

关闭浏览器直接进入主页则需重新登陆

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5715745.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存