Springboot组合SpringSecurity安全插件基于密码的验证Demo!下面的案例,都是基于数据库mysql,用户密码,验证登录的策略demo。
1;引入maven仓库的坐标
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
2:增加配置类,配置基础的参数信息。
package com.example.guan.config;import com.example.guan.service.security.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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 javax.annotation.Resource;@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Resourceprivate CustomUserDetailsService iUserService;protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/get-user").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/user/showLogin").defaultSuccessUrl("/index").permitAll().and().logout().permitAll();}@Autowiredprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//这里的参数类型,必须是符合插件本身的类型才行。必须是UserDetailsService的实现类才行。auth.userDetailsService(iUserService);}
}
声明:
WebSecurityConfigurerAdapter,这个有提示,说该抽象类已经被弃用。
3:需要创建一个实现了接口
UserDetailsService
的类(
CustomUserDetailsService
)类的名字你可以自己定义,但是必须实现这个插件的接口才行。
package com.example.guan.service.security;import com.example.guan.bean.User;
import com.example.guan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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;
import org.apache.commons.codec.digest.DigestUtils;import java.util.ArrayList;
import java.util.List;@Component
public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate IUserService userService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 通过用户名从数据库获取用户信息User user = userService.getOneByUsername(username);if (user == null) {throw new UsernameNotFoundException("用户不存在");}// 得到用户角色String role = user.getRoleinfo();// 角色集合List<GrantedAuthority> authorities = new ArrayList<>();// 角色必须以`ROLE_`开头,数据库中没有,则在这里加authorities.add(new SimpleGrantedAuthority("ROLE_" + role));return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);}
}
4:创建一个测试控制器HelloController.测试一下效果
package com.example.guan.controller;import com.example.guan.bean.User;
import com.example.guan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Autowiredprivate IUserService userInfoService;@GetMapping("/get-user")public User getUser(@RequestParam String username){return userInfoService.getOneByUsername(username);}@PreAuthorize("hasAnyRole('user')") // 只能user角色才能访问该方法@GetMapping("/user")public String user(){return "user角色访问";}@PreAuthorize("hasAnyRole('admin')") // 只能admin角色才能访问该方法@GetMapping("/admin")public String admin(){return "admin角色访问";}}
具体测试结果如下所示:
1:get-user接口的测试效果如下:
如图,这个接口需要带一个参数,username。我使用的是Apifox接口管理软件。