基於spring security實現接口權限控制
- 2019 年 12 月 24 日
- 筆記
基於spring security實現接口權限控制
一、基於註解 (1)在security配置文件上配置@EnableGlobalMethodSecurity(prePostEnabled = true)註解 (2)在具體類上加@PreAuthorize("hasAuthority('admin_s1')")或者方法上加上@PreAuthorize("hasAuthority('admin_s1')") 代碼示例如下
package com.ysh.springboot.test.config; import com.sayo.authlogin.auth.JwtAuthenticationFilter; import com.sayo.authlogin.service.DatabaseUserDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig { @Configuration public static class MySecurityConfig extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("databaseUserDetailService") private DatabaseUserDetailService userDetailsService; @Autowired @Qualifier("authenticationSuccessHandler") private AuthenticationSuccessHandler successHandler; @Autowired @Qualifier("authenticationFailHandler") private AuthenticationFailHandler failHandler; @Autowired @Qualifier("authenticationEntryPointImpl") private AuthenticationEntryPoint entryPoint; @Bean public JwtAuthenticationFilter getJwtAuthenticationFilter(){ return new JwtAuthenticationFilter(); } @Override public void configure(HttpSecurity http) throws Exception { // http.addFilterBefore(getJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().csrf().disable() .authorizeRequests() .antMatchers("/v2/api-docs/**").permitAll() .anyRequest().authenticated() .and().formLogin().loginProcessingUrl("/api/login") .successHandler(successHandler) .failureHandler(failHandler) .and().exceptionHandling().authenticationEntryPoint(entryPoint); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } } }
package com.ysh.springboot.test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ysh.springboot.test.service.UserService; import com.ysh.springboot.test.valueobject.UserView; @RestController @RequestMapping("/api")
//@PreAuthorize("hasAuthority('admin_s1')")
public class UserController { @Autowired private UserService userService; @GetMapping(value = "/user") public UserView getUserByName(@RequestParam("userName") String userName,Authentication au) { System.out.println("11111111111"); System.out.println(au); return userService.getUserByUserName(userName); }
@PreAuthorize("hasAuthority('admin_s1')")
@GetMapping(value = "/user2") public UserView getUserByName2(@RequestParam("userName") String userName,Authentication au) { System.out.println("11111111111"); System.out.println(au); return userService.getUserByUserName(userName); } }
package com.ysh.springboot.test.service; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ysh.springboot.test.domain.User; import com.ysh.springboot.test.repository.UserRepository; import com.ysh.springboot.test.valueobject.UserView; @Service public class UserService { @Autowired private UserRepository userRepository;
@PreAuthorize("hasAuthority('admin_s11')")
@Transactional public UserView getUserByUserName(String userName){ UserView userView = new UserView(); User user = userRepository.findByUserName(userName); userView.setUserName(user.getUserName()); userView.setUserDesc(user.getUserDescription()); List<String> roleCodes = new ArrayList<>(); user.getRoles().stream().forEach(role -> roleCodes.add(role.getRoleCode())); userView.setRoleCodes(roleCodes); return userView; } }
二、基於SecurityConfig配置類
@Override public void configure(HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().csrf().disable() .authorizeRequests() .antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/api/*").access("hasAuthority('admin_s3')")
.anyRequest().authenticated() .and().formLogin().loginProcessingUrl("/api/login") .successHandler(successHandler) .failureHandler(failHandler) .and().exceptionHandling().authenticationEntryPoint(entryPoint); }