目录
一、授权
1.1、基于request的授权
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.sessionManagement(session ->
session.maximumSessions(1)
.expiredSessionStrategy(new MySessionInformationExpiredStrategy())
);//会话并发处理
httpSecurity.cors(Customizer.withDefaults());//跨域处理
httpSecurity.authorizeRequests(
authorize -> authorize
.requestMatchers("/getListUser").hasAuthority("USER_LIST")
.requestMatchers("/addUser").hasAuthority("USER_ADD")
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
);
httpSecurity.formLogin(
//Customizer.withDefaults()//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
);
httpSecurity.logout(logout ->
logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
);
httpSecurity.exceptionHandling(exception ->
exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
httpSecurity.csrf(
csrf -> csrf.disable()
);//关闭csrf功能
return httpSecurity.build();
}
java
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("name",username);
User user = userMapper.selectOne(userQueryWrapper);
if (user == null) {
throw new UsernameNotFoundException(username);
}else {
Collection<GrantedAuthority> collection = new ArrayList<>();
collection.add(()->"USER_LIST");
collection.add(()->"USER_ADD");
return new org.springframework.security.core.userdetails.User(
user.getName(),
user.getPassword(),
user.getEnabled(),
true,//用户账号是否过期
true, //用户凭证是否过期
true, //用户是否被锁定
collection //权限列表
);
}
}
1.2、请求未授权处理
java
public class MyAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
HashMap map = new HashMap<>();
map.put("code",400);
map.put("message","没有权限");
//将信息json化
String jsonString = JSON.toJSONString(map);
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
httpSecurity.exceptionHandling(exception ->
exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())//请求未认证处理
.accessDeniedHandler(new MyAccessDeniedHandler())//
);
1.3、角色分配
java
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("name",username);
User user = userMapper.selectOne(userQueryWrapper);
if (user == null) {
throw new UsernameNotFoundException(username);
}else {
return org.springframework.security.core.userdetails.User
.withUsername(user.getName())
.password(user.getPassword())
.disabled(!user.getEnabled())
.credentialsExpired(false)
.accountLocked(false)
.roles("ADMIN")
.build();
}
}
java
httpSecurity.authorizeRequests(
authorize -> authorize
// .requestMatchers("/getListUser").hasAuthority("USER_LIST")
// .requestMatchers("/addUser").hasAuthority("USER_ADD")
.requestMatchers("/user/**").hasRole("ADMIN")
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
);
1.4、基于方法授权
在配置类中开启
java
@EnableMethodSecurity //开启基于方法的授权
public class MySecurityConfig {}
在方法再次控制
java
@GetMapping("/getListUser")
@PreAuthorize("hasRole('ADMIN')")
public List<User> getListUser(){
return userService.list();
}
@PostMapping("/addUser")
@PreAuthorize("hasRole('TOM')")
public void addUser(@RequestBody User user){
userService.saveUser(user);
System.out.println("添加一次");
}