1.引入依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> 2.配置 application.properties server.port=8086 # spring.application.name=security-sample spring.main.allow-bean-definition-overriding=true spring.mvc.static-path-pattern=/static/** # thymeleaf 配置 spring.thymeleaf.enabled=true spring.thymeleaf.cache=false spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html # 數(shù)據(jù)庫配置 spring.datasource.name=defaultDataSource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_plain?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root123 # 連接池配置 spring.datasource.type=com.zaxxer.hikari.HikariDataSource spring.datasource.hikari.maximum-pool-size=8 spring.datasource.hikari.minimum-idle=4 spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.max-lifetime=50000 spring.datasource.hikari.auto-commit=true spring.datasource.hikari.pool-name=HikariCP # mybatis 配置 mybatis.mapper-locations=classpath:mappers/*xml mybatis.type-aliases-package=com.sky.biz.entity mybatis.configuration.map-underscore-to-camel-case=true 3.定制開發(fā) - 認證流程的 UserDetailsService 說明:UserDetailsService 負責(zé)在 Security 框架中從數(shù)據(jù)源中查詢出2大主要信息, 分別為:認證信息(賬號、密碼)、授權(quán)信息(角色列表、權(quán)限列表)。隨后將這些信息封裝為 UserDetails 對象返回 留作后續(xù)進行登錄認證以及權(quán)限判斷。 @Component public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private PermsService permsService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { BizUser bizUser = userService.queryByUserName(username); // 用戶存在,查詢封裝用戶的"角色與權(quán)限"信息到 UserDetails中,通常自定義封裝對象,繼承 UserDetails的子類 User if(bizUser != null) { // 使用 authorityList 封裝角色權(quán)限信息 List<GrantedAuthority> authorityList = new ArrayList<>(); // 查詢當前用戶 - 角色信息 List<Role> roleList = roleService.getRoleListByUserId(bizUser.getId()); for (Role role : roleList) { authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode())); } // 查詢當前用戶 - 權(quán)限信息 List<Perms> permsList = permsService.getPermsListByUserId(bizUser.getId()); for (Perms perm : permsList) { authorityList.add(new SimpleGrantedAuthority(perm.getPermCode())); } return new SecurityUser(bizUser, authorityList); } return null; } } 4.定義封裝安全信息的實體類:SecurityUser public class SecurityUser extends User { private BizUser bizUser; public SecurityUser(BizUser user, Collection<? extends GrantedAuthority> authorities) { super(user.getUserName(), user.getPassword(), true,true, true, true, authorities); this.bizUser = user; } public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } // get && set public BizUser getBizUser() { return bizUser; } public void setBizUser(BizUser bizUser) { this.bizUser = bizUser; } } 5.自定義密碼校驗的類:PasswordEncoder,這里自由發(fā)揮,根據(jù)各自公司安全需要自定義 主要就是重寫 encode(CharSequence rawPassword) 和 matches(CharSequence rawPassword, String encodedPassword) 方法 如果不想自定義就配置成spring-security提供的 BCryptPasswordEncoder 來處理密碼加密與校驗 6.配置Security @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) // 開啟方法級別的細粒度權(quán)限控制 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; // 配置對 HTTP 請求的安全攔截處理 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/static/**").permitAll() .anyRequest().authenticated() .and().formLogin() .and().csrf().disable() .formLogin().loginPage("/login").loginProcessingUrl("/doLogin") .defaultSuccessUrl("/main") .failureUrl("/fail") .permitAll(); // "/login","/main"與"/fail",都是對應(yīng) html頁面訪問controller跳轉(zhuǎn)路徑 // 用戶權(quán)限不夠,處理并返回響應(yīng) http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { String header = request.getHeader("X-Requested-With"); if("XMLHttpRequest".equals(header)) { response.getWriter().print("403"); // 返回ajax 請求對應(yīng)的 json格式 } else { request.getRequestDispatcher("/error403").forward(request, response); } } }); } @Bean public MyPasswordEncoder passwordEncoder() { return new MyPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new passwordEncoder()); // 或者:auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } } 7.使用加密時: @Autowired private MyPasswordEncoder passwordEncoder; // 方法1: String encodePwd = passwordEncoder.encode(user.getPassword()); // 方法2: String encodePwd = new BCryptPasswordEncoder().encode(user.getPassword()); user.setPassword(encodePwd); userMapper.save(user); 大體整合完成!
文章來源地址http://www.zghlxwxcb.cn/news/detail-695577.html
文章來源:http://www.zghlxwxcb.cn/news/detail-695577.html
到了這里,關(guān)于spring security - 快速整合 springboot的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!