Spring Security(一)认证、受权以及权限控制
之前写过一篇Shiro的,讲解了Shiro的基础用法。原本想做一个系列,但是忙别的去了,一直没搞。因为项目需求,抽空学了一下 Security,分享少量经验和大家共同学习一下
本节目标
搭建一个简单的Web 工程实现以下功能
- 简单的认证、受权功能
- 权限控制(URL匹配的权限控制,方法权限控制,基于Thymeleaf的页面按钮权限)
Demo 技术选型
SpringBoot 2.1.6.RELEASE + Spring Security + JdbcTemplate + Thymeleaf
Security 如何工作
图片.png
和Shiro一样,Security 以过滤器的形式集成到我们的项目中,帮助我们管理客户的权限。本文不做过多原理方面的分析,后续假如有续集为大家讲解
集成Security
在SpringBoot的基础上增加依赖就可
build.gradle
dependencies { ... compile("org.springframework.boot:spring-boot-starter-security") ...}pom.xml
<dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ...</dependencies>但这还远远不够,想要完成我们的需求,还需要做少量工作
简单的认证、受权
@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean @Override public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("123456") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); }}@EnableWebSecurity启用Spring Security 对Web的支持并与SpringMVC集成,中间的过程我们无需关心
再看看上面代码,我们都做了什么?
理解过Shiro的朋友,看到上面的代码是不是感觉很熟习?
首先是URL配置,我们配置
"/"和"home"无需任何访问权限,其他的请求需要受权,并配置了登录和注销我们还需要提供一个 UserDetailsService 的实现来提供客户的认证和受权,上述代码提供了一个简单的基于内存的UserDetailsManager,实际开发中,我们可以自己实现一个UserDetailsService ,下文中会有。
Security 会使用 UsernamePasswordAuthenticationFilter、LogoutFilter 来解决我们的登录和注销请求,默认的登录注销路径为"/login","/logout"我们只提供客户的认证和受权信息就可
这个时候为了方便我们看效果,再增加几个页面
- home.html,所有人可见
src/main/resources/templates/home.html
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example</title> </head> <body> <h1>Welcome!</h1> <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p> </body></html>- hello.html,根据上面的配置这个页面是需要认证后才可以访问的
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Sign Out"/> </form> </body></html>- login.html
其实Security默认为我们提供了一个登录页面,但是为了加深印象,这里我们自己写一个
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head> <title>Spring Security Example </title></head><body><div th:if="${param.error}"> Invalid username and password.</div><div th:if="${param.logout}"> You have been logged out.</div><form th:action="@{/login}" method="post"> <div><label> User Name : <input type="text" name="username"/> </label></div> <div><label> Password: <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign In"/></div></form></body></html>- 最后配置一下URL和模板的映射
@Configurationpublic class MvcConfig implements WebMvcConfigurer { public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/").setViewName("home"); registry.addViewController("/hello").setViewName("hello"); registry.addViewController("/login").setViewName("login"); }}OK 到这里,简单的认证、受权、还有注销完成了
默认情况下,Security登录后会重定向到上一次请求的URL
上述案例源码:
TavenYin/security-example/tree/master/simple-example
关于 UserDetailsService
上述的案例使用的 InMemoryUserDetailsManager,我们在实际开发时不可能使用的。在使用Shiro的时候通常我们会在数据库中拉取客户的认证和受权信息,Security同理
我们自己实现一个 UserDetailsService,权限和角色这里我偷懒了,就没有从数据库拉
public class MyUserDetailsService implements UserDetailsService { private static final String ROLE_PREFIX = "ROLE_"; @Autowired private JdbcTemplate jdbcTemplate; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDO user = null; try { user = jdbcTemplate.queryForObject(Sql.loadUserByUsername, Sql.newParams(username), new BeanPropertyRowMapper<>(UserDO.class)); } catch (DataAccessException e) { e.printStackTrace(); } if (user == null) throw new UsernameNotFoundException("客户不存在:" + username); return User.builder() .username(username) .password(user.getPassword()) // 这里的密码是加密后 .authorities( ROLE_PREFIX +"super_admin", ROLE_PREFIX +"user", "sys:user:add", "sys:user:edit", "sys:user:del", "sys:match", "sys:mm" )// 这里偷懒写死几个权限和角色 .build(); }}并将我们这个新的 UserDetailsService 注册到Security中,并指定密码的加密规则
@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean @Override public UserDetailsService userDetailsService() { return new MyUserDetailsService(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder()); }}Shiro中角色和权限是分开的,但是在Security中存储在一个集合中,角色以 ROLE_ 开头
权限控制
当客户完成了认证,受权之后,通常我们的接口也是有自己的权限的,只有客户的权限匹配上了才可以访问
- 对匹配的URL设置权限
还是上面的configure方法,和Shiro的配置方式很类似
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() // 测试配置URL权限 .antMatchers("/match/**").hasAuthority("sys:match") // 对某URL增加多个权限,可以屡次配置 .antMatchers("/match/**").hasAuthority("sys:mm") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll() .and() ; }- 方法权限 (可用于接口权限)
通过@EnableGlobalMethodSecurity,启用注解
@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用@PreAuthorizepublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {}需要控制权限的方法上增加注解,@PreAuthorize 还可以使用其自带的方法进行校验
@PreAuthorize("hasRole('user')") public Object user() { User user = SecurityUtils.currentUser(); return "OK, u can see it. " + user.getUsername(); }Security 还支持其余的方法权限注解,感兴趣的同学可以到 @EnableGlobalMethodSecurity 类里看一下
- 页面权限控制
增加依赖
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId></dependency><div sec:authorize="hasRole('super_admin')"> super_admin 可见</div><div sec:authorize="hasAuthority('sys:mm')"> sys:mm 可见</div>更多用法参考: thymeleaf/thymeleaf-extras-springsecurity
权限测试这块写了一点demo,但是有点乱,有想参考的朋友可以看一下
TavenYin/taven-springboot-learning/tree/master/spring-security
参考资料
https://spring.io/guides/gs/securing-web/
https://spring.io/guides/topicals/spring-security-architecture/
计划下一篇为大家带来,Security 认证、注销的自己设置扩展
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Spring Security(一)认证、受权以及权限控制