SpringBoot整合SpringSecurity:集中式项目
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
SpringBoot整合SpringSecurity:集中式项⽬sql脚本在resource⽬录下,⽤户密码是1234.
只实现了部分主要功能(认证授权),增删改查没有实现。
pom依赖
注意打包⽅式要改成war包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
配置⽂件
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///security_authority?serverTimezone=UTC
ername=root
spring.datasource.password=1234
mybatis.type-aliases-package=com.wj.springsecurity.domain
mybatis.configuration.map-underscore-to-camel-case=true
.wj.springsecurity.mapper=debug
配置类
@EnableGlobalMethodSecurity(securedEnabled = true)//开启@Secured注解
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login.jsp","/failer.jsp","/css/**","/img/**","/plugins/**","/favicon.ico").permitAll() .antMatchers("/**").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.jsp").loginProcessingUrl("/login")
.successForwardUrl("/index.jsp").failureForwardUrl("/failer.jsp")
.permitAll()
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login.jsp")
.invalidateHttpSession(true)//是否清空session
.permitAll()
.and()
.csrf().disable();
}
/**
* 认证的来源(内存还是数据库)
* @param auth
* @throws Exception
*/
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.inMemoryAuthentication().withUser("user").password("{noop}1234").roles("USER"); erDetailsService(userService).passwordEncoder(passwordEncoder());
}
}
主启动类
@MapperScan("com.wj.springsecurity.mapper")
@SpringBootApplication
public class SpringbootSecurityJspApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSecurityJspApplication.class, args);
}
}
UserService
实体类
SysUser
public class SysUser implements UserDetails {
private Integer id;
private String username;
private String password;
private Integer status;
private List<SysRole> roles;
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
ername = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getId() {
return id;
}
public Integer getStatus() {
return status;
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return ername;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
}
SysRole
注意重写的⽅法要写对。
public class SysRole implements GrantedAuthority {
private Integer id;
private String roleName;
private String roleDesc;
@JsonIgnore
@Override
public String getAuthority() {
return null;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
}
service
接⼝
public interface UserService extends UserDetailsService { }
实现类
@Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userMapper.findByName(username);
}
}
Mapper
public interface UserMapper extends Mapper<SysUser> {
@Select("select * from sys_user where username = #{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roles", column = "id", javaType = List.class,
many = @Many(select = "com.wj.springsecurity.mapper.RoleMapper.findByUid"))
})
public SysUser findByName(String username);
}
public interface RoleMapper extends Mapper<SysRole> {
@Select("select r.id,r.role_name as roleName,r.role_desc as roleDesc " +
"from sys_role r , sys_user_role ur " +
"where uid = #{uid} and r.id = ur.rid")
public List<SysRole> findByUid(Integer uid);
}
权限控制
在controller层:
@Controller
@RequestMapping("/product")
public class ProductController {
@Secured({"ROLE_USER"})
@RequestMapping("/findAll")
public String findAll(){
return "product-list";
}
}
我这⾥踩了⼀个坑,权限必须要是"ROLE_"开头,否则会有问题。
启动项⽬
点击m按钮
输⼊:spring-boot:run,按下enter键
运⾏成功
⽤户名:wj
密码:1234
如果能进⼊系统,说明搭建整合成功。
点击产品管理,能进⼊产品管理界⾯,则权限控制成功。