Spring Security(四):自定义用户认证逻辑

继续接着第二篇文章 《Spring Security(二):三分钟入门HelloWorld 》进行自定义用户认证。

基本思路:自定义SpringSecurity安全框架的配置类,并继承WebSecurityConfigurerAdapter,重写configure方法

 

自定义基本配置


1、【zjj-security-browser 工程】自定义SpringSecurity安全框架的配置类,创建 BrowserSecurityConfig 类

package com.zjj.security.browser;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin() // 定义是否使用表单登录
		.and()
		.authorizeRequests() // 对所有请求进行授权
		
		.anyRequest()	// 任何请求
		.authenticated();// 都需要身份认证
	}
}

2、【zjj-security-browser 工程】配置用户认证逻辑,创建MyUserDetailService类,并实现UserDetailsService接口

package com.zjj.security.browser.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserDetailService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("用户名:" + username);
		// 比较new User() 3个参数、7个参数的区别,详情参看UserDetails
		return new User("zjj", "123456", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
//		return new User("zjj", password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}
}

3、【 zjj-security-demo工程 】启动ZjjSecurityDemoApplication 类main方法,并访问 http://localhost:8080/hi 进行观察

 a、首先会跳转到表单登录页面,这是因为自定义配置了 http.formLogin()  使用表单登录
 b、使用自定义用户名:zjj  密码:123456 登录
 c、登录成功,并重定向到 http://localhost:8080/hi ,展现

hellow zjj

 

 

处理密码加密解密 PasswordEncoder 


1、【zjj-security-browser 工程】修改BrowserSecurityConfig类,注入 PasswordEncoder

package com.zjj.security.browser;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin() // 定义是否使用表单登录
		.and()
		.authorizeRequests() // 对所有请求进行授权
		
		.anyRequest()	// 任何请求
		.authenticated();// 都需要身份认证
	}
}

2、【zjj-security-browser 工程】修改MyUserDetailService类,加密 passwordEncoder

package com.zjj.security.browser.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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.Component;

@Component
public class MyUserDetailService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("用户名:" + username);
		
		String password = passwordEncoder.encode("123456");
		logger.info("数据库密码是:" + password);
		
		// 比较new User() 3个参数、7个参数的区别,详情参看UserDetails
		return new User("zjj", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
//		return new User("zjj", password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}
}

3、【 zjj-security-demo工程 】启动ZjjSecurityDemoApplication 类main方法

 a、访问 http://localhost:8080/hi,首先跳转到登录页面
 b、使用自定义用户名:zjj  密码:123456 登录
 c、登录成功,观察控制台打印(注:控制台每次打印的字符串加密都是不一样的,这是因为进行了盐值加密)

2019-03-19 17:54:36.263  INFO 22216 --- [nio-8080-exec-8] c.z.s.b.service.MyUserDetailService      : 用户名:zjj
2019-03-19 17:54:36.342  INFO 22216 --- [nio-8080-exec-8] c.z.s.b.service.MyUserDetailService      : 数据库密码是:$2a$10$rym2m15hqecqPKiQoKn1nO9HxaziYxygCWiqFEuCft4PC5mEDwpDO

 

自定义登录Html页面


1、【zjj-security-browser 工程】在\src\main\resources下新建文件夹resources,并创建zjj-login.html页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
	<p style="color: red;">自定义登录页面</p>
	<form action="/authentication/form" method="post">
		<table>
			<tr>
				<td>用户名:</td>
				<td><input type="text" name="username"></td>
			</tr>
			<tr>
				<td>密码:</td>
				<td><input type="password" name="password"></td>
			</tr>
			<tr>
				<td colspan="2"><button type="submit">登录</button></td>
			</tr>
		</table>
	</form>
</body>
</html>

2、【zjj-security-browser 工程】修改BrowserSecurityConfig类,指定配置登录页面

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin() // 定义是否使用表单登录
		.loginPage("/zjj-login.html") // 指定html登录页面
                .loginProcessingUrl("/authentication/form") // 自定义登录接口
		.and()
		.authorizeRequests() // 对所有请求进行授权
		.antMatchers("/zjj-login.html").permitAll() // 指定页面不需要进行认证
		.anyRequest()	 // 任何请求
		.authenticated() // 都需要身份认证
		.and()
                .csrf().disable(); // 关闭csrf防护
	}
}

3、【 zjj-security-demo工程 】启动ZjjSecurityDemoApplication 类main方法

 a、访问 http://localhost:8080/hi,首先跳转到登录 http://localhost:8080/zjj-login.html 页面

 b、使用自定义用户名:zjj  密码:123456 进行登录
 c、登录成功,跳转到指定页面


源码下载
Spring Security 码云目录一览

更多内容请关注我的个人博客:http://www.zjjfx68.com/ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值