Table of contents
2. Quick start based on the administrator module SpringSecurity
2.0. First introduce dependencies
2.1. Inherit WebSecurityConfiuraerAdapter
3. Quick start based on the common user module SpringSecurity
3.1. Implement the UserDetailsService interface
3.2. Inherit WebSecurityconfiguraerAdapter
Introduction
SpringSecurity is integrated in SpringBoot 2.3.4.RELEASE, so we only need to introduce startup dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
quick start
The quick start of using SpringSecurity is divided into two steps, because in the process of writing projects in the company, it is divided into front-end and back-end. When using login in the back-end, there is no need to query the database, because the back-end login is controlled by the administrator, and the management Only 1 to 5 members are needed. We need to query the database at the front desk, so I will divide the quick start into two modules, one is the background module and the other is the front desk module.
2. Quick start based on the administrator module SpringSecurity
2.0. First introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.1. Inherit WebSecurityConfiuraerAdapter
WebSecurityConfigurerAdapter
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String password = passwordEncoder().encode("密码");
auth.inMemoryAuthentication().withUser("账号").password(password).roles("");
}
//引入security自带的密码加密
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置认证
http.formLogin().loginPage("/login.html")//配置那个url为登录页面
.loginProcessingUrl("/login")//设置那个是登录的url
.defaultSuccessUrl("/admin/index.html").permitAll()//登录成功去哪?
.failureForwardUrl("/find.html").permitAll()//登录失败去哪?
//退出时删除缓存,并且重定向到login.html页面 在前端默认路径为:/logout .and().requestCache().disable().logout().logoutSuccessUrl("/login.html").permitAll();
//开启frame功能
http.headers().frameOptions().sameOrigin();
//这个可以根据自己需求去添加
http.authorizeRequests().antMatchers(
"/css/**",
"/*.html",
"/img/**",
"/js/**",
"/login",
"/plugins/**"
).permitAll()//制定URL无需保护。
.anyRequest() //其他请求
.authenticated();//需要认证
//关闭csrf跨域
http.csrf().disable();
}
}
2.2. Front-end page
<form action="/login"method="post">
用户名:<input type="text"name="username"/><br/>
密码:<input type="password"name="password"/><br/>
<input type="submit"value="提交"/>
</form>
Note: name must be called: username and password method must be submitted for post action is: /login
After the configuration is completed, you can start the project and start testing. No matter what you access, it will default to the login page you specified. Only after successful login can you access other pages!
3. Quick start based on the common user module SpringSecurity
3.0. Introducing dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.1. Implement the UserDetailsService interface
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
/**
因为公司项目使用的是Dubbo+zookeeper组合,所以我调用的接口在zookeeper中使用这个注解
如果你使用的是单项目的话可以直接通过spring注入的方式,来获取你的mapper接口!
*/
@Reference(version = "1.0.0")
SellerService sellerService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//给当前用户创建权限 可自定义 默认就为这个
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_SELLER");
//通过前端传入的参数获取username,在数据库中查询出来数据
Seller seller = sellerService.findOne(username);
//这个是判断用户的状态,如果没有状态,你只需要判断是否为空即可
if (seller!=null && "1".equals(seller.getStatus())){
return new User(seller.getSellerId(),new BCryptPasswordEncoder().encode(seller.getPassword()),auths);
}else {
throw new UsernameNotFoundException("用户名不存在");
}
}
}
3.2. Inherit WebSecurityconfiguraerAdapter
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//通过数据库查询出来判断账号密码是否相等
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
//注入security自带的加密方式
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置认证
http.formLogin().loginPage("/shoplogin.html")//配置那个url为登录页面
.loginProcessingUrl("/login")//设置那个是登录的url
.defaultSuccessUrl("/admin/index.html").permitAll()//登录成功去哪?
.failureForwardUrl("/shoplogin.html").permitAll()//登录失败去哪?
.and().requestCache().disable().logout().logoutSuccessUrl("/login.html").permitAll();
// 解析前端的 <frame>、<iframe> 标签
http.headers().frameOptions().sameOrigin();
//设置无需保护的路径
http.authorizeRequests().antMatchers(
"/css/**",
"/img/**",
"/js/**",
"/login",
"/plugins/**",
"/seller/addSeller",
"/*.html"
).permitAll()//制定URL无需保护。
.anyRequest() //其他请求
.authenticated();//需要认证
//关闭跨域
http.csrf().disable();
}
}
This picture is the content in the code above and can be ignored.
3.3. Front-end page
<form action="/login"method="post">
用户名:<input type="text"name="username"/><br/>
密码:<input type="password"name="password"/><br/>
<input type="submit"value="提交"/>
</form>
3.4. Obtain the user name managed by Security
@RequestMapping("/name")
public Map<String,String> name(){
//获取被Security管理的username
String name= SecurityContextHolder.getContext().getAuthentication().getName();
//将他保存到map等其他类型中就可以传到前端页面或者通过这个名字查询数据库
Map<String, String> map = new HashMap<>();
map.put("loginName",name);
return map;
}
Ready for testing
Request chain:
When we start the project, the configure(HttpSecurity http) method in 3.2 will be automatically loaded. Then when we enter the login page and submit the post request data to /login through username and password, we will enter the loadUserByUsername(String username) method in 3.1 . To judge between your databases, after the judgment is completed, you will enter the configure(AuthenticationManagerBuilder auth) method in 3.2 and let Security handle whether the login is successful.