一、创建项目
参考:浅试Security
二、实现用户授权
2.1、基于权限进行访问控制
- hasAuthority方法:如果当前的主体具有指定的权限,则返回true,否则返回false。
- hasAnyAuthority方法:如果当前的主体有任何提供的权限的话,则返回true,否则返回false。
Tip:如果返回false,则页面提示http状态码为403,表示请求被拒绝
2.1.1、配置资源的访问权限
在SecurityConfig配置类中设置访问资源的权限的逻辑
package demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Spring Security配置类
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityService securityService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(securityService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置没有权限访问时跳转的自定义页面
http.formLogin() //表单登陆
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //从login.html页面登录成功之后跳转到该路径
.permitAll();
http.authorizeHttpRequests() //授权配置
//配置/test/insert路径只能是拥有insert权限的用户才能访问
.antMatchers("/test/insert").hasAnyAuthority("insert")
.anyRequest() //任何请求
.authenticated(); //所有请求都拦截
http.csrf().disable(); //关闭跨站脚本攻击
}
/**
* 将PasswordEncoder注入到ioc容器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
2.1.2、配置用户被授予的权限
在SecurityService类中添加授权的逻辑(用户被授予的权限)
package demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SecurityService implements UserDetailsService {
@Autowired
@Lazy
private PasswordEncoder encoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据username,去数据库查该用户的信息
if("tom".equals(username)){
//设置的authorityString必须和SecurityConfig中设置的hasAuthority字符串一致
//当前用户具有insert权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("insert");
return new User("tom", encoder.encode("123"), auths);
} else {
throw new UsernameNotFoundException(null);
}
}
}
2.2、基于角色进行访问控制
- hasRole方法:如果用户具有指定角色,则返回true,否则false。
- hasAnyRole方法:如果用户具有指定的任意角色,则返回true,否则返回false。
tip:如果返回false,则页面提示http状态码为403,表示请求被拒绝
2.2.1、配置可以访问资源的角色
在SecurityConfig配置类中设置访问资源的角色的逻辑
package demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Spring Security配置类
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityService securityService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(securityService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置没有权限访问时跳转的自定义页面
http.formLogin() //表单登陆
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //从login.html页面登录成功之后跳转到该路径
.permitAll();
http.authorizeHttpRequests() //授权配置
//配置/test/insert路径只能是拥有insert权限的用户才能访问
.antMatchers("/test/insert").hasAnyAuthority("insert")
//配置/test/info路径只能是拥有admin角色的用户才能访问
.antMatchers("/test/info").hasAnyRole("admin")
.anyRequest() //任何请求
.authenticated(); //所有请求都拦截
http.csrf().disable(); //关闭跨站脚本攻击
}
/**
* 将PasswordEncoder注入到ioc容器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
2.2.2、配置用户被赋予的角色
在SecurityService类中添加授权的逻辑(用户被授予的角色)
package demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SecurityService implements UserDetailsService {
@Autowired
@Lazy
private PasswordEncoder encoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据username,去数据库查该用户的信息
if("tom".equals(username)){
//设置的authorityString必须和SecurityConfig中设置的hasAuthority字符串一致
//当前用户具有insert权限,具有admin角色(角色必须加ROLE_的前缀)
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("insert,ROLE_admin");
return new User("tom", encoder.encode("123"), auths);
} else {
throw new UsernameNotFoundException(null);
}
}
}
三、源代码
Security用户授权.zip