spring boot 中使用spring security阶段小结
1 项目结构图
2 AnyUserDetailsService
package com.fengyntec.config; import com.fengyntec.entity.UserEntity; import com.fengyntec.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; 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.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class AnyUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = userService.getByUsername(username); if (userEntity == null){ System.out.println("用户不存在"); } List<SimpleGrantedAuthority> simpleGrantedAuthorities = createAuthorities(userEntity.getRoles()); UserDetails userDetails = new User(userEntity.getUsername(),userEntity.getPassword(),simpleGrantedAuthorities); return userDetails; } private List<SimpleGrantedAuthority> createAuthorities(String roleStr){ String[] roles = roleStr.split(","); List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>(); for (String role : roles) { simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role)); } return simpleGrantedAuthorities; } }
3 WebSecurityConfig
package com.fengyntec.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; 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; @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AnyUserDetailsService anyUserDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/user/**").hasRole("USER") .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.html") .permitAll() ; } /** * 添加 UserDetailsService, 实现自定义登录校验 */ @Override protected void configure(AuthenticationManagerBuilder builder) throws Exception{ builder.userDetailsService(anyUserDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } }
4 Constant
package com.fengyntec.constant; public interface Constant { public static String ROLE_USER = "ROLE_USER"; }
5 HomeController
package com.fengyntec.controller; import com.fengyntec.service.UserService; import com.google.gson.Gson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @EnableGlobalMethodSecurity(securedEnabled = true) public class HomeController { @Autowired private UserService userService; @GetMapping("/hell") public String hello(SecurityContextHolder holder){ System.out.println(holder.toString()); return new Gson().toJson(holder); } @GetMapping("admin") public String admin(){ return "admin"; } @GetMapping("/vip") @Secured("ROLE_VIP") public String vip(){ return "仅限于vip用户查看"; } @GetMapping("/openVip") public boolean uodateVip(){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); List<GrantedAuthority> updateAuthority = new ArrayList<>(auth.getAuthorities()); updateAuthority.add(new SimpleGrantedAuthority("ROLE_VIP")); Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(),auth.getCredentials(),updateAuthority); SecurityContextHolder.getContext().setAuthentication(newAuth); return true; } }
6 UserEntity
package com.fengyntec.entity; import lombok.Data; @Data public class UserEntity { private Long id; /** * 账号 */ private String username; /** * 密码 */ private String password; /** * 昵称 */ private String nickname; /** * 权限 */ private String roles; }
7 Mapper
package com.fengyntec.mapper; import com.fengyntec.entity.UserEntity; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; @org.apache.ibatis.annotations.Mapper @Component public interface Mapper { @Insert("insert into user(username, password, nickname, roles) values(#{username}, #{password}, #{nickname}, #{roles})") int insert(UserEntity userEntity); @Select("select * from user where username = #{username}") UserEntity selectByUsername(@Param("username") String username); }
8 UserService
package com.fengyntec.service; import com.fengyntec.constant.Constant; import com.fengyntec.entity.UserEntity; import com.fengyntec.mapper.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; @org.springframework.stereotype.Service @Primary public class UserService { @Autowired private Mapper mapper; public boolean insert(UserEntity userEntity){ String username = userEntity.getUsername(); if (exist(username)){ return false; } userEntity.setRoles(Constant.ROLE_USER); int result = mapper.insert(userEntity); return result == 1 ; } private boolean exist(String username){ UserEntity userEntity = mapper.selectByUsername(username); return userEntity != null; } public UserEntity getByUsername(String username) { return mapper.selectByUsername(username); } }