springboot整合spring-security實現簡單的登錄注銷


參考地址:https://www.jianshu.com/p/18875c2995f1

1、引入maven依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2、Security 配置類 說明登錄方式、登錄頁面、哪個url需要認證、注入登錄失敗/成功過濾器

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 注入 Security 屬性類配置
     */
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 注入 自定義的  登錄成功處理類
     */
    @Autowired
    private MyAuthenticationSuccessHandler mySuccessHandler;
    /**
     * 注入 自定義的  登錄失敗處理類
     */
    @Autowired
    private MyAuthenticationFailHandler myFailHandler;

    /**
     * 重寫PasswordEncoder  接口中的方法,實例化加密策略
     * @return 返回 BCrypt 加密策略
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //登錄成功的頁面地址
        String redirectUrl = securityProperties.getLoginPage();
        //basic 登錄方式
//      http.httpBasic()

        //表單登錄 方式
        http.formLogin()
                .loginPage("/authentication/require")
                //登錄需要經過的url請求
                .loginProcessingUrl("/authentication/form")
                .successHandler(mySuccessHandler)
                .failureHandler(myFailHandler)
                .and()
                //請求授權
                .authorizeRequests()
                //不需要權限認證的url
                .antMatchers("/authentication/*",redirectUrl).permitAll()
                //任何請求
                .anyRequest()
                //需要身份認證
                .authenticated()
                .and()
                //關閉跨站請求防護
                .csrf().disable();
        //默認注銷地址:/logout
        http.logout().
                //注銷之后 跳轉的頁面
                logoutSuccessUrl("/authentication/require");
    }

3、自定義登錄成功和失敗的處理器

(1)、登錄成功

@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
         logger.info("登錄成功");
          //將 authention 信息打包成json格式返回
            httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登錄成功");
 } }

(2)、登錄失敗

@Component
@Slf4j
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.info("登錄失敗");
           //設置狀態碼
            httpServletResponse.setStatus(500);
            //將 登錄失敗 信息打包成json格式返回
            httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登錄失敗:"+e.getMessage());
 } }

4、UserDetail 類 加載用戶數據 , 返回UserDetail 實例 (里面包含用戶信息)

@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根據進行登錄
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登錄用戶名:"+username);
        String password = passwordEncoder.encode("123456");
        //User三個參數   (用戶名+密碼+權限)
        //根據查找到的用戶信息判斷用戶是否被凍結
        log.info("數據庫密碼:"+password);
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

5、登錄路徑請求類,.loginPage("/authentication/require")

@RestController
@Slf4j
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public class BrowerSecurityController {

    /**
     * 把當前的請求緩存到 session 里去
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * 重定向 策略
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 注入 Security 屬性類配置
     */
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 當需要身份認證時 跳轉到這里
     */
    @RequestMapping("/authentication/require")
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //拿到請求對象
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null){
            //獲取 跳轉url
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引發跳轉的請求是:"+targetUrl);

            //判斷 targetUrl 是不是 .html 結尾, 如果是:跳轉到登錄頁(返回view)
            if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                String redirectUrl = securityProperties.getLoginPage();
                redirectStrategy.sendRedirect(request,response,redirectUrl);
            }
        }
        //如果不是,返回一個json 字符串
        return new SimpleResponse("訪問的服務需要身份認證,請引導用戶到登錄頁");
    }

6、postman請求測試

(1)未登錄請求

(2)、登錄

 (3)、再次訪問

 (4)、注銷


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM