欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

基于springsecurity實(shí)現(xiàn)登錄注銷功能過程解析

這篇文章主要介紹了基于spring security實(shí)現(xiàn)登錄注銷功能過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

我們提供的服務(wù)有:做網(wǎng)站、網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、常德ssl等。為上千多家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的常德網(wǎng)站制作公司

1、引入maven依賴

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

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

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

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

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

  /**
   * 重寫PasswordEncoder 接口中的方法,實(shí)例化加密策略
   * @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")
        //登錄需要經(jīng)過的url請求
        .loginProcessingUrl("/authentication/form")
        .successHandler(mySuccessHandler)
        .failureHandler(myFailHandler)
        .and()
        //請求授權(quán)
        .authorizeRequests()
        //不需要權(quán)限認(rèn)證的url
        .antMatchers("/authentication/*",redirectUrl).permitAll()
        //任何請求
        .anyRequest()
        //需要身份認(rèn)證
        .authenticated()
        .and()
        //關(guān)閉跨站請求防護(hù)
        .csrf().disable();
    //默認(rèn)注銷地址:/logout
    http.logout().
        //注銷之后 跳轉(zhuǎn)的頁面
        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("登錄失敗");

      //設(shè)置狀態(tài)碼
      httpServletResponse.setStatus(500);
      //將 登錄失敗 信息打包成json格式返回
      httpServletResponse.setContentType("application/json;charset=UTF-8");
      httpServletResponse.getWriter().write("登錄失敗:"+e.getMessage());
 } }

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

@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

  @Autowired
  private PasswordEncoder passwordEncoder;

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

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

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

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

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

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

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

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

6、postman請求測試

(1)未登錄請求

基于spring security實(shí)現(xiàn)登錄注銷功能過程解析

(2)、登錄

基于spring security實(shí)現(xiàn)登錄注銷功能過程解析

(3)、再次訪問

基于spring security實(shí)現(xiàn)登錄注銷功能過程解析

(4)、注銷

基于spring security實(shí)現(xiàn)登錄注銷功能過程解析

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前文章:基于springsecurity實(shí)現(xiàn)登錄注銷功能過程解析
文章源于:http://www.chinadenli.net/article18/gpejdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)網(wǎng)站維護(hù)外貿(mào)網(wǎng)站建設(shè)動態(tài)網(wǎng)站微信公眾號企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)