一、导入依赖
<!-- SpringSecurity 对 Web 应用进行权限管理 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 配置 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 标签库 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
二、环境搭建
在web.xml中加入springSecurityFilterChain过滤器(名称不可变),如果配置无效,需考虑将Spring IOC容器和SpringMVC IOC容器合二为一。
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、编写项目
1.配置SpringSecurity
1)基于xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<security:http>
<security:http-basic/>
<security:form-login/>
<security:intercept-url pattern="/**" access="isAuthenticated()"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="tom" password="123456" authorities="ROLE_USER"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
2)基于配置类
测试方法:基于内存
// 开启配置类注解
@Configuration
// 开启基于web的security
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//基于内存
auth
.inMemoryAuthentication()
.withUser("tom")
.password("123456")
.roles("ADMIN", "练气")
.and()
.withUser("jeck")
.password("123456")
.authorities("UPDATE")
.roles("练气", "元婴")
;
}
@Override
protected void configure(HttpSecurity security) throws Exception {
//引入jdbc
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
security
.authorizeRequests() //对请求进行授权
.antMatchers("/index.jsp", "/layui/**") //对index.jsp授权
.permitAll() //无条件访问
.antMatchers("/level1/**")
.hasRole("Admin")
.antMatchers("/level2/**")
.hasRole("User")
.and()
.authorizeRequests() //对请求进行授权
.anyRequest() //任意请求
.authenticated() //需要登录后才能访问
.and()
.formLogin() //使用表单形式登录
.loginPage("/index.jsp") //指定登录页
.permitAll() //设置登录页所有人可以访问
.loginProcessingUrl("/do/login.html") //自定义登录请求路径
.usernameParameter("loginAcct") //自定义登录账号参数名
.passwordParameter("userPswd") //自定义登录密码参数名
.defaultSuccessUrl("/main.html") //自定义登陆成功默认路径
.and()
.csrf()
.disable() // 禁用csrf功能
.logout()
.logoutUrl("/do/logout.html")
.logoutSuccessUrl("/index.jsp")
.and()
.exceptionHandling()
.accessDeniedPage("/WEB-INF/views/no_auth.jsp")
.and()
.rememberMe() //开启记住我功能
.tokenRepository(jdbcTokenRepository) //保存到数据库
;
}
}
真正配置:基于数据库
//盐值加密
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService) //自定义用户权限
.passwordEncoder(passwordEncoder)
;
}
@Component
public class AppUserDetailsService implements UserDetailsService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//从数据库中查询Admin对象
String sql="SELECT id,loginacct,userpswd,username,email,createtime FROM t_admin WHERE loginacct = ?";
List<Admin> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), username);
Admin admin = list.get(0);
//给Admin设置角色权限信息
List<GrantedAuthority> authorities= AuthorityUtils.createAuthorityList("ROLE_ADMIN","UPDATE");
return new User(username,admin.getUserpswd(),authorities);
}
}
本文详细介绍了如何在Spring Boot项目中整合Spring Security进行权限管理。首先,通过XML配置文件或配置类展示了如何配置Spring Security,包括HTTP基本认证、表单登录以及拦截URL的访问权限。接着,演示了基于内存和数据库的用户认证方式,以及如何自定义用户权限和服务。最后,提供了基于数据库的完整配置示例,包括密码加密、用户权限从数据库加载等。

2459

被折叠的 条评论
为什么被折叠?



