修改和完成SpringSecurity的登录功能

1、配置SpringSecurity改变默认表单页面但是流程不变

添加loginPage、loginProcessingUrl方法

java 复制代码
	//做拦截
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 请求授权
		http.formLogin()
		.loginPage("/require")//自定义登录页面
		.loginProcessingUrl("/loginPage")//security默认处理流程  表单:action="/loginPage" method="post"
		.and().authorizeRequests()
		//授权放行
		.antMatchers("/loginPage","/require","/registerVisitor","/judgeSMS","/sendSMS","/visitorRegister","/visitorLogin","/index","/mood","/findMood","/findAllBlog","/findAllAlbum","/findAllArchives","/link",
				"/css/**","/editor.md/**","/images/**","/js/**","/layer/**","/social/**","/statics/**","/upload/**").permitAll()
		//所有请求
		.anyRequest()
		//都需要身份认证
		.authenticated().and()
		//43、使用Layer打开select-mood子页面并配置SpringSecurity允许Iframe嵌入页面 
		.headers().frameOptions().disable().and()
		//跨站请求伪造的防护
		.csrf().disable()
		//添加我们所写的spring social配置
		.apply(zzzSocialSecurityConfig);
	}
java 复制代码
//在MainController中添加
	@RequestMapping("/require")
	public String require() {
		return "/login.html";
	}

表单提交

html 复制代码
<form action="/loginPage" method="post" class="login100-form validate-form">

测试:SecurityUserService中打印用户名

java 复制代码
	//用户名密码登录
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO 在数据库中找
		System.out.println(username);
		
		...
	}

测试成功

2、完成访客登录功能且拓展登录失败与登录成功的Handler

访客登录

java 复制代码
package com.zzz.blog.service;

import ...

@Component
public class SecurityUserService implements UserDetailsService{

	//加密方法返回值
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private VisitorService visitorService;
	
	//用户名密码登录
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO 在数据库中找
		System.out.println(username);
		
		User user = userService.findUserByUsername(username);
		if(user != null) {
			//将用户信息给SpringSecurity管理
			return new SocialUser(user.getUsername(), passwordEncoder.encode(user.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
		}
		
		Visitor visitor = visitorService.findVisitorByUsername(username);
		if(visitor != null) {
			return new SocialUser(visitor.getUsername(), passwordEncoder.encode(visitor.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("VISITOR"));
		}
		
		throw new UsernameNotFoundException("用户不存在!!");
	}

}

拓展登录失败与登录成功的Handler的事件处理,添加handler

java 复制代码
package com.zzz.blog.config;

import ...

//安全配置类
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	//SpringSecurity加密方法返回值
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Autowired
	private SpringSocialConfigurer zzzSocialSecurityConfig;
	
	@Autowired
	private LoginSuccessHandler loginSuccessHandler;
	@Autowired
	private LoginFailureHandler loginFailureHandler;
	
	//做拦截
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 请求授权
		http.formLogin()
		.loginPage("/require")//自己的登录页面
		.loginProcessingUrl("/loginPage")//security默认处理流程  表单登录提交路径:action="/loginPage" method="post"
		.failureHandler(loginFailureHandler) //登录失败的Handler
		.successHandler(loginSuccessHandler)  //登录成功的Handler
		.and().authorizeRequests()
		//授权放行
		.antMatchers("/loginPage","/require","/registerVisitor","/judgeSMS","/sendSMS","/visitorRegister","/visitorLogin","/index","/mood","/findMood","/findAllBlog","/findAllAlbum","/findAllArchives","/link",
				"/css/**","/editor.md/**","/images/**","/js/**","/layer/**","/social/**","/statics/**","/upload/**").permitAll()
		//所有请求
		.anyRequest()
		//都需要身份认证
		.authenticated().and()
		//43、使用Layer打开select-mood子页面并配置SpringSecurity允许Iframe嵌入页面 
		.headers().frameOptions().disable().and()
		//跨站请求伪造的防护
		.csrf().disable()
		//添加我们所写的spring social配置
		.apply(zzzSocialSecurityConfig);
	}
	
}
java 复制代码
package com.zzz.blog.handler;

import ...

@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		// TODO 登录成功后的处理
		
		super.onAuthenticationSuccess(request, response, authentication);
	}
	
}
java 复制代码
package com.zzz.blog.handler;

import ...

@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler{

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		// TODO 登录失败后的处理
		
		super.onAuthenticationFailure(request, response, exception);
	}

}
相关推荐
魔道不误砍柴功2 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2342 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨2 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
种树人202408192 小时前
如何在 Spring Boot 中启用定时任务
spring boot
测开小菜鸟3 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity4 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天4 小时前
java的threadlocal为何内存泄漏
java
caridle4 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^5 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋35 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx