多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**1. pom中引入spring-boot-starter-security依赖** ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency> </dependencies> ``` **2. 实现UserDetailsService接口定义认证逻辑** ```java @Service public class LoginServiceImpl implements UserDetailsService { @Autowired private AccountService accountService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //根据username查询数据库 Account account = accountService.findByUsername(username); if (account == null) { throw new UsernameNotFoundException("用户名不存在!"); } //用户权限 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin"); return new User(username, account.getPassword(), authorities); } } ``` **3. 实现接口AuthenticationEntryPoint以屏蔽Spring Security重定向登录页面** 在非前后端分离的情况下,如果没有登录,则会自动重定向到登录页面。这里是前后端分离,需要返回的是 json 字符串,所以需要实现接口 AuthenticationEntryPoint 以屏蔽 Spring Security 重定向登录页面。 ```java @Component public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException { Map<String, Object> map = new HashMap<>(16); map.put("code", 1000); map.put("message", "未登录!"); response.setContentType("text/json;charset=utf-8"); response.getWriter().write(JSON.toJSONString(map)); } } ``` **4. 继承Spring Security核心配置类:WebSecurityConfigurerAdapter** ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationEntryPoint authenticationEntryPoint; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //注册UserDetailsService接口 auth.userDetailsService(userDetailsService()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/account/show") .hasAuthority("admin") .and() .exceptionHandling() //注册AuthenticationEntryPoint .authenticationEntryPoint(authenticationEntryPoint); //允许跨域请求 http.cors(); //关闭csrf http.csrf().disable(); } /** * 注入UserDetailsService接口实现类 */ @Override @Bean public UserDetailsService userDetailsService() { return new LoginServiceImpl(); } /** * 注入BCryptPasswordEncoder密码处理器 * @return */ @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` **5. SpringBoot配置允许跨域请求** ```java @Configuration public class CustomWebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*") .allowCredentials(true); } } ``` **6. 创建一个controller层方便演示** ```java @RestController @RequestMapping("/account") public class AccountController { @RequestMapping("/show") public String show() { return "Account!"; } } ``` **7. postman演示结果** 未登录访问 http://localhost:8080/account/show ,可见成功返回我们自定义的 json 数据。 ```json { "code": 1000, "message": "未登录!" } ```