# SpringSecuirtyLearn **Repository Path**: maoqingcode/spring-secuirty-learn ## Basic Information - **Project Name**: SpringSecuirtyLearn - **Description**: No description available - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-29 - **Last Updated**: 2021-11-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #### 一 SpringSecurity基本原理 ![](readme.assets/image-20201129200935376-1606652040760.png) **FilteSecurityInterceptor** : 依据用户自定义配置 来进行最终判断 ,若通过则防护服务,若不通过则抛出对应异常 在该位置打断点: InterceptorStatusToken token = super.beforeInvocation(fi); **ExceptionTranslationFilter**: 用来捕获后面过滤器所抛出的异常 #### 二 自定义登录请求 [分支customLogin] ​ 在前后端分离的情况下 我们应该动态去修改 登录页面, ​ 前端 向后端发送登录请求 ​ 后端 根据前端发送的请求 : ​ 1 如果 后缀是.html 结尾 若为登录,则将该请求 重定向到 登录页面 ​ 2 如果 不是.html 结尾 ,则向前端发送 JSON请求 告诉前端未认证,前端发送登录页面请求 ###### 1 使用配置文件 能够实现自定义的登录页面 ```java package com.mao.security.core.properties; // 定义Properties 属性 在 application.properties 中 将自定义的属性映射到该pojo对象上 public class BrowserProperties { private String signUpUrl = "/imooc-signUp.html"; private String loginPage = "/login"; } ``` ```java package com.mao.security.core.properties; /** * 加载application.proerties 中 mao.security相关的属性值 */ @ConfigurationProperties(prefix = "mao.security") public class SecurityProperties { private BrowserProperties browser=new BrowserProperties(); public BrowserProperties getBrowser() { return browser; } public void setBrowser(BrowserProperties browser) { this.browser = browser; } } ``` ```java package com.mao.security.core; @Configuration @EnableConfigurationProperties(SecurityProperties.class)//开启加载propertis属性 public class SecurityCoreConfig { } ``` ###### 2 处理登录请求 完成前端请求逻辑的判断 ```java package com.mao.security; @RestController public class BrowserSecurityController { private Logger logger= LoggerFactory.getLogger(getClass()); // 获得访问请求路径 private RequestCache requestCache=new HttpSessionRequestCache(); // 实现重定向 private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy(); //加载自定义的properties 属性 @Autowired private SecurityProperties securityProperties; /** * 是登录请求 由该方法处理 */ @RequestMapping("/mao/loginPage") @ResponseStatus(code = HttpStatus.UNAUTHORIZED) public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { SavedRequest savedRequest=requestCache.getRequest(request,response); if(savedRequest !=null){ String targetUrl=savedRequest.getRedirectUrl(); logger.info("引发跳转的请求:"+targetUrl); if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){ redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage()); } } return new SimpleResponse("访问需要身份认证,请引导到用户登录页"); } } ``` ###### 3 secuirtyConfig 配置文件 ```java package com.mao.security; @Configuration public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private SecurityProperties securityProperties; @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/mao/loginPage") //使用自定义路由 可以使用.html 也可以使用url .loginProcessingUrl("/a/login") .and() .authorizeRequests() .antMatchers("/mao/loginPage",securityProperties.getBrowser().getLoginPage()).permitAll() .anyRequest() .authenticated() .and() .csrf().disable(); //使用自定义页面时 会出现csrf问题 此时先禁用 } } ``` ###### 4 自定义UserDetailService ```java package com.mao.web.security; @Component public class MyUserDetailServiceImpl implements UserDetailsService { @Autowired private PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { String password=passwordEncoder.encode("123456"); return new SocialUser(username,password,true,true,true,true , AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); } } ``` ###### 5 自定义 application.properties ```properties spring.datasource.driver-class-name = com.mysql.jdbc.Driver spring.datasource.url= jdbc:mysql://127.0.0.1:3306/imooc-demo?useUnicode=yes&characterEncoding=UTF-8&useSSL=false spring.datasource.username = root spring.datasource.password = root spring.session.store-type = none #开启spring security security.basic.enabled = true #自定义的登录请求 mao.security.browser.loginPage=/customePage.html ```