在使用 Spring Security 做权限管理的时候,授权登录成功后,一般是跳转到首页。但是我们想再授权成功一瞬间做一些额外的操作,比如记录日志,添加 Session 等。
具体做法如下
创建 SecurityConfig 类,继承 WebSecurityConfigurerAdapter
重写 protected void configure(HttpSecurity http) 方法
在里面添加如下代码
第 7 行-第 19 行是自定义操作
完整代码如下
其他代码不是本文的重点,这里省略。
本文地址:https://liuyanzhao.com/7898.html
具体做法如下
创建 SecurityConfig 类,继承 WebSecurityConfigurerAdapter
重写 protected void configure(HttpSecurity http) 方法
在里面添加如下代码
- .successHandler(new AuthenticationSuccessHandler() {
- @Override
- public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
- Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- if (principal != null && principal instanceof UserDetails) {
- UserDetails user = (UserDetails) principal;
- //1、添加 Session
- httpServletRequest.getSession().setAttribute("userDetail", user);
- //2、写入日志
- logger.info("【用户已登录】" + user.getUsername());
- //3、写入数据库login_record表
- LoginRecord loginRecord = new LoginRecord();
- loginRecord.setLoginIp(IPUtil.getIpAddr(httpServletRequest));
- loginRecord.setLoginTime(System.currentTimeMillis());
- loginRecord.setUser((User) user);
- loginRecordRepository.save(loginRecord);
- //4、页面跳转到首页
- httpServletResponse.sendRedirect(ctx);//即 /forum
- }
- }
- })
第 7 行-第 19 行是自定义操作
完整代码如下
- package com.liuyanzhao.forum.config;
- import com.liuyanzhao.forum.entity.LoginRecord;
- import com.liuyanzhao.forum.entity.User;
- import com.liuyanzhao.forum.repository.LoginRecordRepository;
- import com.liuyanzhao.forum.service.impl.CustomUserService;
- import com.liuyanzhao.forum.util.IPUtil;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.authentication.AuthenticationProvider;
- import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
- import org.springframework.security.config.BeanIds;
- import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
- import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- /**
- * 安全配置类
- *
- * @author 言曌
- * @date 2018/1/23 上午11:37
- */
- @EnableWebSecurity
- @EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Value("${server.servlet.context-path}")
- public String ctx;
- private static final String KEY = "liuyanzhao.com";
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- private LoginRecordRepository loginRecordRepository;
- /**
- * 自定义UserDetailsService,从数据库中读取用户信息
- *
- * @return
- */
- @Bean
- public CustomUserService customUserDetailsService() {
- return new CustomUserService();
- }
- @Bean
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();// 使用 BCrypt 加密
- }
- @Bean
- public AuthenticationProvider authenticationProvider() {
- DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
- authenticationProvider.setUserDetailsService(customUserDetailsService());
- authenticationProvider.setPasswordEncoder(passwordEncoder()); // 设置密码加密方式
- return authenticationProvider;
- }
- @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
- /**
- * 自定义配置
- */
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() // 都可以访问
- .antMatchers("/h2-console/**").permitAll() // 都可以访问
- .antMatchers("/login").permitAll() // 都可以访问
- .antMatchers("/admin/**").hasRole("ADMIN") // 需要相应的角色才能访问
- .and()
- .formLogin() //基于 Form 表单登录验证
- .loginPage("/login").failureUrl("/login?error=true") // 自定义登录界面
- .successHandler(new AuthenticationSuccessHandler() {
- @Override
- public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
- Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- if (principal != null && principal instanceof UserDetails) {
- UserDetails user = (UserDetails) principal;
- //1、添加 Session
- httpServletRequest.getSession().setAttribute("userDetail", user);
- //2、写入日志
- logger.info("【用户已登录】" + user.getUsername());
- //3、写入数据库login_record表
- LoginRecord loginRecord = new LoginRecord();
- loginRecord.setLoginIp(IPUtil.getIpAddr(httpServletRequest));
- loginRecord.setLoginTime(System.currentTimeMillis());
- loginRecord.setUser((User) user);
- loginRecordRepository.save(loginRecord);
- //4、页面跳转到首页
- httpServletResponse.sendRedirect(ctx);//即 /forum
- }
- }
- })
- // .defaultSuccessUrl("/")//登陆成功页面,需要去掉,否则不会执行上面的方法
- .and().rememberMe().key(KEY) // 启用 remember me
- .and().exceptionHandling().accessDeniedPage("/403"); // 处理异常,拒绝访问就重定向到 403 页面
- http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
- http.csrf().ignoringAntMatchers("/ajax/**"); // 禁用 H2 控制台的 CSRF 防护
- http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
- }
- /**
- * 认证信息管理
- *
- * @param auth
- * @throws Exception
- */
- @Autowired
- public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(customUserDetailsService());
- auth.authenticationProvider(authenticationProvider());
- }
- }
其他代码不是本文的重点,这里省略。
本文地址:https://liuyanzhao.com/7898.html
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏